AsyncTask on Rescue!!!


“android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.”

erm… would you mind sorting this out too.

Well, that’s what I do here, don’t I?

Ok, so what I did wrong here?

You did the most common mistake every new Android developer do first time, so no need to panic. Even I did it several times, before I got to know about it. Mistakes make you learn new things. Those who didn’t make any mistakes, didn’t do anything at all. You should remember that.

Tell me when you start talking about Android again.

Oh, I caught in the flow ūüėȬ† So the main reason about why you got this exception is already mentioned there. Only those thread can access the View which created them. Mostly it’s the UI thread aka main thread. So you can’t create a new thread and call a method on any view in it.

I thought Android supports multi-threading???

Yeah, it does, but there’s a limitation to it. Android can’t allow multiple threads to access the Views, cause the timings of completion of threads are uncertain and due to this, the view, which actually makes the whole activity’s User Interface, would have looked odd, if allowed to be modified by more than one thread.

So there’s no way I can access the views from separate threads??

As far as I know, there’s no way. However I never ran into any situation which needs the view to be updated by separate threads and I don’t think you need it too. Before I get spammed by such kind of situations, let me clear my point. The most common situation where the view needs to be updated by separate thread is when you are loading certain data and on completion of it you want to update the view, such as dismissing a ProgressDialog or calling the setText() method on TextView.

Yeah, I am trying to do the same thing.

Gotcha then!!! Well, then your app can be saved by the almighty AsyncTask easily.

Now what is it? Don’t tell me to read the title this time, I’ve already read it.

Smart you!! Well AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. In other words, you can easily jump in and out to UI thread and any other thread using this class easily.

Would you mind telling me how to use it?

Yeah I was about to do it. But before that you should read what the official doc says about it. To use AsyncTask you have to subclass it. So the first step is to make a class and extend AsyncTask. Remember that AsyncTask supports generics, so if you want to supply parameters to it, use them. However in normal situation you won’t need it, thus I am making all parameters as void in my example.

Yeah, You are talking business now. Where’s the code example?

Suppose you are loading data from a web-service using a method loadData(). And till the method runs you want to show a ProgressDialog which should get dismiss on completion of loading. The code for the same would be:

class LoadingTask extends AsyncTask<Void,Void,Void>{
      protected Void onPreExecute() {
          ProgressDialog dialog=new ProgressDialog(getActivityContext());
          dialog.setMessage("Loading data ...");
          dialog.show();
      }
      protected Void doInBackground() {
          loadData();
      }
      protected Void onPostExecute() {
          dialog.dismiss();
     }
 } 

And if you want to update the UI thread in between the loading, you need to call publishProgress() method, which takes an argument usually an Integer, about how much loading has been done. The call to publishProgress() will ultimately call onProgressUpdate() method which runs on UI thread. So jumping in and out of UI thread is easier with this. On completion of you loading, the onPostExecute() gets called.

The thing to remember here is all methods except doInBackground(), gets called on UI thread, where the Views are accessible, thus the loading taks should be in doInBackground() and updating view should be in either onProgressUpdate() (when you want to update View in between the loading) or in onPostExecute() (whne you want to update View after the loading is finished). onPreExecute() gets called before the loading starts, and runs on UI thread too.

Ok I got it, but how do I start the task?

You need to make an object of the class we just made and call execute() method on it. Remember that the execute() method can take parameters to be passed in the task, but generally I declare all the variables needed as class variable, so never needed it. The type of parameters passed is decided by the generics we declare in the AsyncTask. You can notice that all the method takes variable arguments.

LoadingTask task=new LoadingTask();
task.execute(); 

Ok, Finally I got it, thanks for saving my app again.

If this post helped you then just share this post as much as you can, so that we can save more lives. You can also click on any of the share button available and share this post with your friends, collegues or anyone who can get benefit with it. You can post your questions and comments below and, can also vote up this post.

I want to hear more from you.

You can check my¬†stackoverflow¬†profile and look for answers I posted there (probably vote on them too ūüėČ ). You can also ask your questions there and provide me a link to answer them. If you want a complete blog post on them, leave me a comment, and I’ll get back to you soon.

Thanks for listening,

Abhi,

The Creator

profile for Creator at Stack Overflow, Q&A for professional and enthusiast programmers

android_logo

Android Development – bringToFront() and sendToBack() on View


What’s new this time?

This time there’s another most wanted answer for a most asked question. I’ve seen this question many times on programming forums and stackoverflow. The question here is to play with z ordering of the views or in laymen terms getting the bringToFront() and sendToBack() methods on a view.

CRAP!! There’s already a bringToFront() method in View class.

Yes there is. The problem is you’ll get to use it just one time on one view in a single layout. And no there’s no sendToBack() method, so you can’t send the View to back after getting it to the front.

I’ll call bringToFront() on another View and the previous one will be automatically send to background ūüėČ

*sighs* Smart,ah?? But you didn’t read it properly. You get just one bringToFront() call per layout. There’s a thing called z ordering of views and you can modify it just once. It’s not Microsoft Word where you have lot’s of methods and no layers like Photoshop :p

What’s z ordering now?

This is out of the scope of this post, however I might explain this in later posts. If you still want to know about it, just imagine it like having an order of which view comes above which other one.

Ok, I know you got the answer this time too. Just say it and let us know.

You got it this time. Well it’s not a official method, it’s a trick. Some people have given ideas like clearing the layout by calling removeAllChild() method on it and recreate the layout. However I got cleaner method than this. The trick here is to play with the z-ordering and create a new one for every view when you want to change there appearance. In the above trick they used to recreate the whole layout for this, hwoever this can be acheived by just refreshing the views.

CODE!! Where’s the code???

Yeah I know what you were waiting for. Here’s the code sample for you:

Suppose you have four views, slightly overlapping each other. The views could be any subclass of View class, such as TextView, ImageButtons, ImageView, EditText, even the layouts. Thus the code to bring each view to the front would be like this:-

View view1,view2,view3,view4; 
//code to initiate and putting the views in layout 
//Code to get view1 in foreground 
view1.bringToFront(); 
view1.invalidate(); 
view2.invalidate(); 
view3.invalidate(); 
view4.invalidate(); 
//Code to get view2 in foreground 
view2.bringToFront(); 
view1.invalidate(); 
view2.invalidate(); 
view3.invalidate(); 
view4.invalidate(); 
//Code to get view3 in foreground 
view3.bringToFront(); 
view1.invalidate(); 
view2.invalidate(); 
view3.invalidate(); 
view4.invalidate(); 
//Code to get view4 in foreground 
view4.bringToFront(); 
view1.invalidate(); 
view2.invalidate(); 
view3.invalidate(); 
view4.invalidate();

Oh! I almost forgot the invalidate() method. It’s a nice and simple trick, and I do not need to touch the layouts at all.

I like to do things in a simple way, and I think now you’ll get to do it the same way.

You saved my life again. Is there anything I can do for you?

Just share this post as much as you can, so that we can save more lives. You can also click on any of the share button available and share this post with your friends, collegues or anyone who can get benefit with it. You can post your questions and comments below and, can also vote up this post.

I want to hear more from you.

You can check my¬†stackoverflow¬†profile and look for answers I posted there (probably vote on them too ūüėČ ). You can also ask your questions there and provide me a link to answer them. If you want a complete blog post on them, leave me a comment, and I’ll get back to you soon.

Thanks for listening,

Abhi,

The Creator

profile for Creator at Stack Overflow, Q&A for professional and enthusiast programmers


A well-written guide for developers, interested in Android devepoment

Thomas' Interesting Blog

I really like doing Android development and over the past few months I’ve done quite a bit of it but I found at the beginning that some things didn’t seem to be entirely logical that were quite important despite the fact that I already had a vast programming knowledge. Here is a list of things I reckon are useful for learning Android development:

  • Java experience: I don‚Äôt think that you need to know loads of Java to develop Android apps but I would say it is important that you at least know the syntax and roughly how to do things. Experience in a similar language like C# or C++ would probably get you by, just so long as you know the difference between a package, class and that kind of thing
  • Experience in another object-orientated language: Some experience in another language would also be useful because despite the fact that‚Ķ

View original post 370 more words

Android Development – ListView v/s TableLayout with CheckBoxes


What’s this is all about?

Do you have CheckBox in your ListView’s each row?? Then you’ll know what I mean here. Those who have experience with CheckBox in ListView knows the recycling of objects in ListView more than anyone else.

So what’s this recycle thing going on here??

ListView in general have multile rows in them, sometimes more than what a normal screen can show at one time. As anyone with enough experience with Layouts know that more the Layouts in your activity, more time will it take to load. So to fasten up loading time in ListView, android developers added a recycle feature in it. The feature recycles every row which is not currently displayed on the screen and when the user scrolls or flings loads them back. This feature load the ListView faster and make it look smoother.

So why do I care about what a ListView does, only when I have CheckBox in a row??

You will have to worry about the recycle feature cause you would wanted to persist the state of the CheckBoxes, i.e. when a user selects a CheckBox and scrolls down and up, they should see the CheckBox as selected, but in reality it doesn’t happen. Why? Dude, I just told you, it’s RECYCLED and created again, so there’re new object of Checkbox everytime you scroll or fling.

I bet there must be methods or XML tags in ListView to disable the recycling. 

Go ahead! Buy a magnifier and try to find it, and when you get that, please tell me about that too. I guess you know what I mean here, there’s no method in ListView to disable recycling. No,no the¬†ITEM_VIEW_TYPE_IGNORE¬†constant won’t help you too.

OMG!!! I am doomed now. I had a ListView with CheckBoxes. All the codes ready, what should I do?

No worries! There’re many tricks available to help you, like saving the checkbox data into a boolean array or in SharedPreferences. But the thing is it’s hard to persist the state, as you have to work hard with RecyclerListener in ListView to save and retrieve the CheckBox state.

Then I must suicide now, I have to submit my project tomorrow and I won’t be able to do it. I am gonna die….¬†(Sorry for being so dramatic ūüėČ )

Well, you don’t need to die, not at least for this. If you have read the Title of this blog properly, you’ll come to know what I mean. There’s a rescue for you. TableLayout!!!!

Erm… How will I be able to Use it??

It’s easy. If you have even a little bit experience with dynamic Layout creation, you’ll be able to handle it easily, don’t worry if you don’t know what it means. I’ll give you a sample code to work on too.

I heard sample code…

Here you go –

XML:-

<ScrollView 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 
<TableLayout  
android:id="@+id/table"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"> 
</TableLayout> 
</ScrollView> 

Code excerpt in Java:-

TableLayout table=(TableLayout)findViewByid(R.id.table);
ArrayList<CheckBox> cbData=new ArrayList<CheckBox>(); 
for(int i=0;i<rowCount;i++){
 TextView t1=new TextView(this); 
 t1.setText("Text1");
 TextView t2=new TextView(this);
 t2.setText("Text2");  
 CheckBox cb=new CheckBox(this); 
 TableRow row=new TableRow(this); 
 row.addView(t1); 
 row.addView(t2); 
 row.addView(cb); 
 cbData.add(cb); 
 table.addView(row);
}

I didn’t got it :/

Well I’ve created XML layout which you need to set in the setContentView(HERE). Although it’s just part of it, as you still need to put it into some Layout for proper formatting. The Tablelayout is been put into a vertical ScrollView, to have a scrolling effect on it. In the java file, we run a loop for every row we need. We created 2 textviews and one checkbox per row, set value in them, created a TableRow, added our components to the row and added the row to the TableLayout. Interesting thing to note here is, we used ArrayList to have a list of objects for the CheckBoxes being used. You can get data,set clicks, listens to the event, etc. using it and you could use ArrayList for any component you need to access later in the activity.

What benefit I got using TableLayout instead of ListView?

GOSH!! How many times I have to tell you. It’s recycling thing we have discussed earlier :p . However the real thing here is, the code you have seen above may be all you need to have a working scolling list. That’s it, no Custom Adapter, no different XML for each component, and no caching code at all. The only thing defers our own list from the original list is, we don’t have that yellow highlighting effect on touch for each row yet, but I am sure you’ll be able to find a better work around (Don’t expect me to do your homework or you too, how will you learn then ūüėČ )

Is there any drawbacks of using it? I mean they always creep in to good hacks.

You are a smart fellow, ain’t you? Well yeah, there is one drawaback, it doesn’t recycle your rows xD .

Err… what do you mean? I thought I wanted to disable recycling.

yes you wanted to, but think about it, why would Google put recycle feature in it? To save the initial loading time and free up unsued resources. Thus, as the Layout theory says, “More the Layouts you have, More you’ll regret it having”. Which means, every increase in Layout count, makes your activity to wait more for loading. There’re work arounds available, such as Lazy-Loading (Don’t worry I’ll cover it in next blog) or Delayed-Loading. However untill you have more than 30 rows, you won’t care for it.

Thank you so much, you saved my life. How can I contribute back?

Click on any of the share button available and share this post with your friends, collegues or anyone who can get benefit with it. You can post your questions and comments below and, can also vote up this post.

I want to hear more from you.

You can check my stackoverflow profile and look for answers I posted there (probably vote on them too ūüėČ ). You can also ask your questions there and provide me a link to answer them. If you want a complete blog post on them, leave me a comment, and I’ll get back to you soon.

Thanks for listening,

Abhi,

The Creator

profile for Creator at Stack Overflow, Q&A for professional and enthusiast programmers

Rotate a Bitmap using matrix


If you are an Android app developer and is working on a game or some other animation project, chances are you might find giving animation to the bitmaps. And when the animation is to rotate the bitmap, the problem increases manifolds. There’re several ways in which you can achieve this objective, such as using RotateAnimation class, but they sometime confuses me, so I use matrix (Mr. Anderson??) ¬†argument of Bitmap constructor. This makes it easier to do. let me show it to you with an example:

Note: I am using this code in the custom View, and using separate method for returning the Matrix. You can have separate class for Bitmap and can call it from there.

public void onDraw(Canvas c){
    Paint p=new Paint();
    Bitmap bm=BitmapFactory.decodeResource(getResources(), R.drawable.bitmap);
    c.drawBitmap(bm, rotateMe(), p);
    invalidate();
}

public Matrix rotateMe(){
    Matrix mtx=new Matrix();
    mtx.postRotate(deg,bm.getWidth()/2,bm.getHeight()/2);
    mtx.postTranslate(x, y);  //The coordinates where we want to put our bitmap
    deg=deg-10; //degree of rotation
    return mtx;
}

Kindly comment your suggestions and questions about this.

Thanks