Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

27 December 2010

[Newbie] NullPointerException when calling findViewById

Well this one really took me quiet some time to solve it. When ever I called findViewById whitin my Activity I got a bloody NullPointerException :(

Here is the code that causes the NullPointerException.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <-- That causes the NullPointerException

        setContentView(R.layout.display);        
    }
} 
 
The solution of course is very easy and was mainly caused by the lack of my Android knowledge. Android of course only can access elements within a layout after it the layout is explicitly set. Therefore I had to set the layout using setContentView(..) and after that the Activity can access the TextView targetDisplay. So the fix was unbelievably easy as you can see in the listing below.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display); // do this first

        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <--No NullPointerException anymore                
    }
}

22 February 2010

My Android must have apps selection

Recently I have bought the new Google Nexus One (US Version). Here is a small must have collection of Android apps which I find quiet useful so far.
  • ASTRO File Manager - A very nice tool to manage your file on your SD card.
  • NetSentry - NetSentry keeps track of how much data is transferred over each network interface available to your Android system.
  • Daily Dilbert - Well there is nothing more to say :)
  • Google Maps - Nice new edition for Nexus One introducing a navigation system
  • TweetCast - A nice Twitter client
All apps can be found at the Android Market.