Tuesday, August 28, 2012

UnknownHostException - Connection to the internet problem

If you are trying to connect to the internet using one of Android's HTTP Clients, but when you do so in your code you get java.net.UnknownHostException, it means your application doesn't have the permission to connect to the internet. To resolve it, add the INTERNET permission to your application's AndroidManifest.xml file. Follow these steps if you are using Eclipse:

  1. Open your AndroidManifest.xml
  2. Click on the Permission tab
  3. Click on Add... then choose "Uses Permission"
  4. From the list of permissions choose "android.permission.INTERNET"
  5. Save and re-run your application

Thursday, August 9, 2012

NullPointerException/IllegalStateException thrown when calling findViewById()


So you're trying to get a reference to a View (TextView, Button, ...etc.) in your Java code using findViewById(). But once you access the view -by calling View.setText() for example-  the application crashes and an 'IlligalStateException' is thrown in LogCat with a 'NullPointerException'  shown in the dump. Here are the two most probable causes of this issue and their solutions:
  1.  Check whether you're calling findViewById() before setContentView(). If so, just place the statement after setContentView(), and you're set.
    You were getting a null in this case because the view you're tying to access from XML is not yet inflated by setContentView(). You can only access a view after it's been inflated on the screen. By calling setContentView() before findViewById(), you guarantee that the view is already inflated.

  2. If you were actually calling findViewById() after setContentView(), but still getting the exception, then you're probably calling the wrong findViewById(). Check which context you have inflated the layout to. For example, if you're building a Dialog from a resource inside an Activity class, then you have to call dialog.getWindow().setContentView(resourceId). Otherwise, you would be calling this.findViewById(), where this refers to the parent Activity and not the built Dialog. Fix this by calling the Dialog's findViewById() to tell Android to look for the resource in the correct inflated layout:
    Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.custom_dialog);
    TextView tv = (TextView) dialog.findViewById(R.id.textView1);