Cross Platform Development Unleashed


You took a long break.

I know, and I am sorry for the same. I  was so busy in shifting to a new job and adapting to a new city, that I hardly got the time for any blogs.

So, no Android this time?

I know you like my Android tutorial posts, but hey learning a new thing is never bad for you ūüėČ

So what’s new in this post?

You’re talking business pretty soon. This post is about cross platform development for mobile apps.

Cross…what?

Cross platform. It means that you just have to write codes in single language for all major mobile platforms available.

You must be joking, is it even possible? And anyways why I need to bother about that?

Yes it is. And this a great technology to use. For example suppose you developed an application for Android platform in Java (Android version). Your application got successful, now your company wants the same application to be launched on iOS too. You didn’t know anything about Objective C, but you took help of some good book and finally able to rewrite the whole code in a different language. But what will you do when you need to port the application on¬†Bada,Windows Phone, Blackberry or some future platform? Will you learn a separate language for each one of them?

erm… We have a separate developers for separate technologies in our company.

So you want to waste your company’s time or money for reinventing the wheel again? Just for porting an existing application on different platform?

Well, I’ve experienced the same issue many times. But what can be done in this case?

*sighs* Can you please read the title of this post again?

 

Oh yeah, cross platform stuff!! So tell me what is it all about and how can I make my life easier with this?

So finally you are speaking English. Cross platform development tools chooses a single language and gives the ease of deploying on more than one platform with the same code.

Do they all use a common language?

There are two kinds of Cross Platform tools available in the market. First one uses the native WebView to show the HTML5 and JavaScript content. Since almost all mobile platforms have WebView so it’s easier to code in HTML5+JavaScript and port to all of them. The second category belongs to the classic C++ community. Since it is the most popular language for development, so every platform supports Native Development in C++.

Is there any advantage of using one type over other?

Yes there is. Coding in HTML5+JS is much easier than coding in C++ for most of the time, when you just need to show some web-content to the user via your app. But when you need to get your hands dirty and want the hardware level access of the phone mostly for games, coding in C++ is best option out there. I am a Game developer, so I’d focus mostly on the C++ part of the Cross Platform stuff.

Why C++? I mean we could have chosen Java.

Because it’s a kind of universal language. Most of the game developers still uses C++ for the freedom they get with it. Java still couldn’t reach there, despite being a cleaner language, because it’s not a Middle Level Language like C and C++ and doesn’t given enough customization option available in C++. Though there’re some frameworks available which supports Java and even C# too.

Great!! So can you tell me some examples of the cross mobile platform development frameworks?

There are many in the market, although The most notable in the first category are Phonegap, Titanium and in second category are Marmalade (formerly¬†known as AirPlay) . My¬†favorite¬†in it is Marmalade which allows coding in C++ and gives direct access to OpenGL library, which is a plus point for any game development. With it’s recent 6.0 SDK, you can now code in HTML5 too. It uses Phonegap standards for this, so if someone knows Phonegap, he/she can work with Marmalade too.

So Marmalade is the best choice, right?

Well I wouldn’t say that. Marmalade SDK is not free, though it provides a 90 days evaluation license, but you can’t commercially deploy apps using evaluation license, although it’s not that costly, if you are serious about your app. The license starts at $149, but the Indie license which costs at $499 is what you’ll need for a serious development. This might not be a major issue for you, but it might be for some individual developers. The second issue which I found in it, is there are very little help available on the internet about marmalade. Asking on Stackoverflow will not get you anything (Probably I am the one who’ll end up answering your question). The only tutorial i found apart from the official one is the drmop one. It’s a good tutorial but still not complete. So if you are a pro-game developer, than it’s best engine you’ll ever find.

So how can I find more information on Marmalade, I mean who’ll save my life now?

I’ll try to share my learnings on the framework, as soon as I can get some more time for this. Keep looking at this place.

Do any popular app uses Marmalade?

Cut the rope, Plants v/s Zombies, NFS Shift… Do I need to say anything else. Read here for more info…

Thanks for the info.

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 on Stack Exchange, a network of free, community-driven Q&A sites

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

A little inflation is good for economy?


What is inflation?

Inflation is defined as sustained increase in the general level of prices for goods and services and measured as an annual percentage increase.

In other words, inflation reduces the purchasing power of your money. For example if the inflation rate is 2% annually, the Re.1 toffee will cost you Rs.1.02 next year.

Is inflation bad?

Inflation can be good or bad in certain conditions. Inflation often works as ‚ÄėInflationary spiral‚Äô. This happens when prices rise, so firms have more profits, so they hire more workers, this sends wages up, so people have more money to spend on higher priced goods, so demand increases, and the prices keep going up.

So how bad an upward inflationary spiral can be? Currently the rate of inflation in Zimbabwe is 231 million percent, just because of upward inflationary spiral. It’s called as Hyper-inflation.

A downward inflationary spiral is worse than an upward one. People get laid off, spend less, prices get cheaper, which leads to people waiting to make purchases as they think that prices will continue to fall, so firms cut costs and lay off workers to reduce prices further, but consumers have less money to spend so they still don’t buy, so more people get laid off, and so on. The negative inflation is called as Deflation.

A deflation may seem like a good thing in the eye of an average consumer, it can lead to collapse of any economy to the ground. As most economists say a hyper-inflation is always better than deflation, because deflation is almost impossible to control unlike hyper-inflation.

Why little inflation is better?

A little inflation (around 3-5%) is always considered as good for overall growth of economy. Some of the reasons for the same are as following:

  • The consumer always expects the prices of goods to increase, so they spend more frequently, which increases demand and provide profitability to the manufacturers.
  • A little inflation is a sign of growing and healthy economy.
  • Inflation always works as a lubricant for any shock to economy and help it to recover. For example in a recession time cutting wages are considered more profitable than cutting jobs, but the earlier is not accepted easier than the later, and as we know job cuts are always bad for economy. But if there‚Äôs inflation in economy, employers just need to provide lesser raise than inflation rate and no one would mind.
  • Inflation drives people to invest their money, instead of locking them up, because each day reduces the purchasing power of money and it‚Äôs better to invest than loose purchasing power.
  • Investment helps companies or government to raise money for growth easier.

So now the question is ‚Äėwhen a little inflation is good for economy?‚Äô and the answer is ‚Äėalways‚Äô.