Thursday 14 June 2012

Android: Learning to walk... and then programmatically add TableRows to a TableLayout

I have had some long spent nights trying to learn developing for Android... LayoutParams... oh you light of my life, LayoutParams...

One recent problem I have been facing is the TableRow widget I intend on populating with data scraped from the web...  store it in a ArrayList<String> and pop it into the TableRow as necessary.

I did buy an idiots guide to Android Development... and I gently set it aside and started Google-ing how to accomplish what I wanted an android app to do.  If you are struggling, Google is your friend...  and just like real life... some friends take you down the wrong path, and others have just what you need.

http://stackoverflow.com/questions/3200691/dynamically-add-tablerow-to-tablelayout

import android.widget.TableRow.LayoutParams;
//import android.widget.RelativeLayout.LayoutParams; 

Just like dfetter88 mentions in his/her answer... ensure you are importing the right thing.

So the background, before getting into the gritty for loop, is that I have scraped data from the web and stored it into an arraylist.  So here's my scratch;
ArrayList<String> prices = getPrice (doc);
for(int i =0; i<prices.size(); i++)
{
    Log.d("PRINT", prices.get(i));
    //RelativeLayout RLay = new RelativeLayout(getParent());
    TableRow TR = new TableRow(getApplicationContext());
    TR.setId(10);
    TR.setLayoutParams(lp);
    TextView price = new TextView(getApplicationContext());
    price.setId(20);
    price.setLayoutParams(lp);
    price.setText(prices.get(i));
    TR.addView(price);
    TLay.addView(TR, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
I had a difficult time wrapping my head around the context argument.  Because this for-loop was triggered by a button click, the context was changed and you couldn't use the term THIS...  which refers to the current object...  and the current object in that situation is BUTTON...  so you can't very well create a new TableRow within the Button context, so I had to use getApplicationContext()...

I think that is explained right, but then again... I really SHOULD read the Android Developer book.

Another really cool trick I learned is to import the Log "module"
import android.util.Log;
This will help you troubleshoot issues while you are testing.  you use it like this;

Log.d("LEVEL1","about to go through the loop... buckle up.");
 LEVEL1 is just the Tag you can assign to the log...  makes it really handy.  Eclipse is a super powerful tool that you definitely need to have if you want to explore android development... There are at least a gajillion resources at your disposal.

Here's where you go to get started: http://developer.android.com/guide/index.html  Do it up.





No comments:

Post a Comment