Tuesday, December 11, 2012

How to make an Activity fullscreen??

There are two ways to make an activity fullscreen,

In your OnCreate method in the activity class,


getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);

From AndroidManifest.xml:

<activity android:name=" "

---

----

android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />




Tuesday, December 4, 2012

Clickable links for textview inside Listview - Android

How to make a URL/link clickable in a textview which is inside a Listview?


Let us assume that you are binding your Listview to a custom adapter. In that case, the following piece of code goes into your getView method call:
Code:
textView.setText(Html.fromHtml(item.gettext()));
textView.setAutoLinkMask(Linkify.WEB_URLS);
Took me sometime to find this out :)


Thursday, November 29, 2012

ASyncTask Tutorial - Android


ASyncTask is an abstract class that allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers..

AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor,ThreadPoolExecutor and FutureTask.

I found this excellent tutorial about Async Task,


The AsyncTask
  1. onPreExecute takes place on the main thread and is the first slice of bread. It sets up the task, prepares a loading dialog, and warns the user that something is about to happen.
  1. doInBackground is the meat of this little task sandwich. This method is guaranteed by Android to run on a separate background thread. This is where the majority of your work takes place.
  1. onPostExecute will be called once your work is finished (again, on the main thread), and the results produced by the background method will be passed to it. This is the other slice of bread.
private class ImageDownloader
extends AsyncTask<String, Integer, Bitmap>{
protected void onPreExecute(){
//Setup is done here
}
@Override
protected Bitmap doInBackground(String... params) {
//TODO Auto-generated method stub
try{
URL url = new URL(params[0]);
HttpURLConnection httpCon =
(HttpURLConnection)url.openConnection();
if(httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
return BitmapFactory.decodeStream(is);
}catch(Exception e){
Log.e("Image","Failed to load image",e);
}
return null;
}
protected void onProgressUpdate(Integer... params){
//Update a progress bar here, or ignore it, it's up to you
}
protected void onPostExecute(Bitmap img){
ImageView iv = (ImageView)findViewById(R.id.remote_image);
if(iv!=null && img!=null){
iv.setImageBitmap(img);
}
}
protected void onCancelled(){
}
}
public void onCreate(Bundle extras){
super.onCreate(extras);
setContentView(R.layout.image_layout);
id = new ImageDownloader();
id.execute("http://wanderingoak.net/bridge.png");
}


How to Make It Work for You

  • The type of parameter that will be passed into the class. In this example AsyncTaskcode, I’m passing one string that will be the URL, but I could pass several of them. The parameters will always be referenced as an array no matter how many of them you pass in. Notice that I reference the single URL string as params[0].
  • The object passed between the doInBackground method (off the main thread) and theonProgressUpdate method (which will be called on the main thread). It doesn’t matter in the example, because I’m not doing any progress updates in this demo, but it’d probably be an integer, which would be either the percentage of completion of the transaction or the number of bytes transferred.
  • The object that will be returned by the doInBackground method to be handled by theonPostExecute call. In this little example, it’s the bitmap we set out to download.
private class ImageDownloader extends
AsyncTask<String, Integer, Bitmap>{
Onpreexecute
protected void onPreExecute(){
}
Doinbackground
protected Bitmap doInBackground(String... params) {
}
Showing your Progress
protected void onProgressUpdate(Integer... params){
//Update a progress bar here, or ignore it, it's up to you
}
Onpostexecute
protected void onPostExecute(Bitmap img){
ImageView iv = (ImageView)findViewById(R.id.remote_image);
if(iv!=null && img!=null){
iv.setImageBitmap(img);
}
}
A Few Important Caveats

  • Downloading small amounts of data specific to one particular activity
  • Loading files from an external storage drive (usually an SD card)
  • Any acquired data that may pertain to more than one activity shouldn’t be acquired through an AsyncTask. Both an image that might be shown on more than one screen and a list of messages in a Twitter application, for example, would have relevance outside a single activity.
  • Data to be posted to a web service is also a bad idea to put on an AsyncTask for the following reason: Users will want to fire off a post (posting a photo, blog, tweet, or other data) and do something else, rather than waiting for a progress bar to clear. By using an AsyncTask, you’re forcing them to wait around for the posting activity to finish.
  • Last, be aware that there is some overhead for the system in setting up the AsyncTask. This is fine if you use a few of them, but it may start to slow down your main thread if you’re firing off hundreds of them.

At its core, the AsyncTask is an abstract class that you extend and that provides the basic framework for a time-consuming asynchronous task.
The best way to describe theAsyncTask is to call it a working thread sandwich. That is to say, it has three major methods for which you must provide implementation.
That’s the gist of the asynchronous task. There are more-complicated factors that I’ll touch on in just a minute, but this is one of the fundamental building blocks of the Android platform (given that all hard work must be taken off the main thread).
Take a look at one in action, then we’ll go over the specifics of it:
That, dear readers, is an asynchronous task that will download an image at the end of any URL and display it for your pleasure (provided you have an image view onscreen with the ID remote_image). Here is how you’d kick off such a task from the onCreate method of your activity.
Once you call execute on the ImageDownloader, it will download the image, process it into a bitmap, and display it to the screen. That is, assuming your image_layout.xml file contains an ImageView with the ID remote_image.
The AsyncTask requires that you specify three generic type arguments (if you’re unsure about Java and generics, do a little Googling before you press on) as you declare your extension of the task.
Here’s the line in which all three objects are declared:
In this example, these are the classes that will be passed to your three major methods.
onPreExecute is usually when you’ll want to set up a loading dialog or a loading spinner in the corner of the screen (I’ll discuss dialogs in depth later). Remember, onPreExecute is called on the main thread, so don’t touch the file system or network at all in this method.
This is your chance to make as many network connections, file system accesses, or other lengthy operations as you like without holding up the phone. The class of object passed to this method will be determined by the first generic object in your AsyncTask’s class declaration. Although I’m using only one parameter in the code sample, you can actually pass any number of parameters (as long as they derive from the saved class) and you’ll have them at your fingertips when doInBackground is called. Once your long-running task has been completed, you’ll need to return the result at the end of your function. This final value will be passed into another method called back on the main UI thread.
There’s another aspect of the AsyncTask that you should be aware of even though I haven’t demonstrated it. From within doInBackground, you can send progress updates to the user interface. doInBackground isn’t on the main thread, so if you’d like to update a progress bar or change the state of something on the screen, you’ll have to get back on the main thread to make the change.
Within the AsyncTask, you can do this during the doInBackground method by callingpublishProgress and passing in any number of objects deriving from the second class in the AsyncTask declaration (in the case of this example, an integer). Android will then, on the main thread, call your declared onProgressUpdate method and hand over any classes you passed to publishProgress. Here’s what the method looks like in the AsyncTaskexample:
As always, be careful when doing UI updates, because if the activity isn’t currently onscreen or has been destroyed, you could run into some trouble.
The work has been finished or, in the example, the image has been downloaded. It’s time to update the screen with what I’ve acquired. At the end of doInBackground, if successful, I return a loaded bitmap to the AsyncTask. Now Android will switch to the main thread and call onPostExecute, passing the class I returned at the end of doInBackground. Here’s what the code for that method looks like:
I take the bitmap downloaded from the website, retrieve the image view into which it’s going to be loaded, and set it as that view’s bitmap to be rendered. There’s an error case I haven’t correctly handled here. Take a second to look back at the original code and see if you can spot it.
Typically, an AsyncTask is started from within an activity. However, you must remember that activities can have short life spans. Recall that, by default, Android destroys and re-creates any activity each time you rotate the screen. Android will also destroy your activity when the user backs out of it. You might reasonably ask, “If I start an AsyncTask from within an activity and then that activity is destroyed, what happens?” You guessed it: very bad things. Trying to draw to an activity that’s already been removed from the screen can cause all manner of havoc (usually in the form of unhandled exceptions).
It’s a good idea to keep track of any AsyncTasks you’ve started, and when the activity’sonDestroy method is called, make sure to call cancel on any lingering AsyncTask.
There are a few cases in which the AsyncTask is perfect for the job:
Make sure, basically, that the data you’re moving with the AsyncTask pertains to only one activity, because your task generally shouldn’t span more than one. You can pass it between activities if the screen has been rotated, but this can be tricky.
There are a few cases when it’s not a good idea to use an AsyncTask:


  • Any acquired data that may pertain to more than one activity shouldn’t be acquired through an AsyncTask. Both an image that might be shown on more than one screen and a list of messages in a Twitter application, for example, would have relevance outside a single activity.
  • Data to be posted to a web service is also a bad idea to put on an AsyncTask for the following reason: Users will want to fire off a post (posting a photo, blog, tweet, or other data) and do something else, rather than waiting for a progress bar to clear. By using an AsyncTask, you’re forcing them to wait around for the posting activity to finish.
  • Last, be aware that there is some overhead for the system in setting up the AsyncTask. This is fine if you use a few of them, but it may start to slow down your main thread if you’re firing off hundreds of them.


Sunday, November 25, 2012

RuntimeException: Unable to instantiate application [ANDROID]

When I run the Android app in Eclipse IDE I'm getting below exception in LogCat,


11-25 11:15:28.252: E/AndroidRuntime(19850): FATAL EXCEPTION: main
11-25 11:15:28.252: E/AndroidRuntime(19850): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.LoadedApk.makeApplication(LoadedApk.java:482)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3949)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.ActivityThread.access$1300(ActivityThread.java:127)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.os.Handler.dispatchMessage(Handler.java:99)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.os.Looper.loop(Looper.java:137)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.ActivityThread.main(ActivityThread.java:4511)
11-25 11:15:28.252: E/AndroidRuntime(19850): at java.lang.reflect.Method.invokeNative(Native Method)
11-25 11:15:28.252: E/AndroidRuntime(19850): at java.lang.reflect.Method.invoke(Method.java:511)
11-25 11:15:28.252: E/AndroidRuntime(19850): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-25 11:15:28.252: E/AndroidRuntime(19850): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-25 11:15:28.252: E/AndroidRuntime(19850): at dalvik.system.NativeStart.main(Native Method)
11-25 11:15:28.252: E/AndroidRuntime(19850): Caused by: java.lang.NullPointerException
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:362)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.LoadedApk.getClassLoader(LoadedApk.java:305)
11-25 11:15:28.252: E/AndroidRuntime(19850): at android.app.LoadedApk.makeApplication(LoadedApk.java:474)

Solution: [From StackOverlow]


This is a verbose error message raised by underlying framework when dalvik re-install .apk file and trying to reuse or recycle the previous opened activity/view from the same package.. if you haven't closed the previous installed app yet). It has nothing to do with your app, moreover, it is very unlikely that your app will get freezed or crashed cause by this verbose error message on end user's device.
It seems that this dalvik verbose error log only happend on Android 4.0 system, I've tested it myself on Android 3.2 and 2.3.3 running environment, where you cannot replicate to get this message shown on neither of them. A similar question has been discussed before at here and someone has filled a bug report in Android Issues Tracker.
I don't think you should concern too much about this verbose error log at the moment, if you look more logs before and after this red error in Logcat, you can see the full story and find that the previous opened activity/view (which are marked as died state) get killed and the newly re-installed one get poped ultimately.

Scrollbar in LinearLayout - Android

If you want add a scrollbar in your linearlayout, wrap the linearlayout with <ScrollView>

Note: Eventhough you have lots of items on the screen, Scroll will not be visible in Linearlayout unless you add it within ScrollView

Tuesday, November 20, 2012

Error parsing XML: unbound prefix - Android



If you get an error "Error parsing XML: unbound prefix" in your XML file, then you should add the following code in your first node,

xmlns:android="http://schemas.android.com/apk/res/android"

like the following,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>



TextView - Bold or Italic - Android

Below is the code that makes a Textview bold or italic


strings.xml
<resources>
    <string name="username"><u><b><i>Peter</i></b></u></string>
</resources>


To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/username"
/>



or In your JAVA code,
   TextView textView=new TextView(this);
    textView.setText(R.string.username);


If you're making use of Dynamic Text, the below code would help
  String tempString="SomeString";
  TextView text=(TextView)findViewById(R.id.text);
  SpannableString spanString = new SpannableString(tempString);
  spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
  spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
  spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
  text.setText(spanString);

SD card - Android


Below is the Android code that checks if SD card is available or not.. Also it checks if the SD card has free memory or not..


private void checkExternalStorageState() {
     String state = Environment.getExternalStorageState();
     if (Environment.MEDIA_MOUNTED.equals(state)) {
        mExternalStorageAvailable = mExternalStorageWriteable = true;
     } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        mExternalStorageAvailable = true;
       mExternalStorageWriteable = false;
     } else {
       mExternalStorageAvailable = mExternalStorageWriteable = false;

}




Sunday, November 18, 2012

Show/Hide of elements - Android

It is easy to show or hide elements in Android..

For example to hide a button,

findViewById(R.id.someButton).setVisibility(View.GONE);

And to make it visible,

findViewById(R.id.someButton).setVisibility(View.VISIBLE);


Saturday, November 17, 2012

android.os.NetworkOnMainThreadException



android.os.NetworkOnMainThreadException exception in Android code??

This exception is thrown when an application attempts to perform a networking operation on its main thread.. 

If your code works in Android 2.x but throws this exception on Android 3.0 and above is because HoneyComb, Ice Cream Sandwich, JellyBean are much stricter about abuse against the UI Thread.. To prevent this exception you need to run the same code in ASyncTask..


The explanation as to why this exception occurs is well documented on the Android developer's site:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

Thursday, November 15, 2012

Loading Icon in Activity TitleBar


How to show a loading icon in the activity titlebar?

Add the following code in your MainActivity class,

@Override
public void onCreate(Bundle icicle) {
   super.onCreate(icicle);
   requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
   setContentView(R.layout.your_layout);
}

then wherever you want

// then, you can do this to show the icon
setProgressBarIndeterminateVisibility(true);


//or to hide it
setProgressBarIndeterminateVisibility(false);

Note: Make sure to use requestWindowFeature before setContentView.



Hello World!!

Hey folks,

This is a hello world post :) Just to make sure that everything works fine!!

I'll share the issues that faced during my Android dev. and the fixes for the same.. Hope this is useful for others as well!!

Happy reading :)

Naveen