Blog Archives

Simple Android Animation on View GONE/VISIBLE

If you just want a better transition view on GONE / VISIBLE rather than the default Android show/hide, I came across  some simple trick to make a simple animation using TranslateAnimation class.

*Note: For a better transitioning, you can use animationlistener , and setVisibility onAnimationStart() or onAnimationEnd().

// View to be animate (I use ImageView as example here)
ImageView imageView = (ImageView)findViewById(;

Below are the methods to set view from VISIBLE to GONE

// To animate view slide out from left to right
public void slideToRight(View view){
TranslateAnimation animate = new TranslateAnimation(0,view.getWidth(),0,0);
// To animate view slide out from right to left
public void slideToLeft(View view){
TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);

// To animate view slide out from top to bottom
public void slideToBottom(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());

// To animate view slide out from bottom to top
public void slideToTop(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight());


Android Dynamic listview updates and append

I just finished my android code on generating never ending listview and just want to share what I have. It will be nice if someone out there can help me recycle my listview properly. This is not a complete solution, but should be good enough for someone to pick up the idea on how to implement it.

I will create a layout for my footer to go into

<LinearLayout xmlns:android=""
 android:text="Loading more items..."/>

Then, you will need to append the footer to your listview. In my case I put it under my onCreate();

lv = (ListView)findViewById(;
lv.addFooterView(((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listviewfooter, null, false));

Now we need to set our listview listener so when it reach our footer view, it can grab additional items.

lv.setSelection(listviewselection); // This line is to position your list view so it does not jump to first in list after updating.
lv.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

//get the last item that is visible on the screen
int lastItemInScreen = firstVisibleItem + visibleItemCount;

//I set a flag here to ask if the list require more items from the server
if((lastItemInScreen == totalItemCount) && flg_shouldLoad){

flg_shouldLoad = false;
listviewselection = firstVisibleItem;
Thread thread = new Thread(null, loadMoreItems);

Following, I will need a runnable to get my item from my server

//Runnable to load the items
private Runnable loadMoreItems = new Runnable() {
public void run() {

At last make sure you do a check for onclicklistener for listview to ignore the last item of your adapter, so you will not have a indexoutofbound exception.

Sharing Facebook Object across multiple activities (Invalid Application ID Error)

I encounter an issue where I tried to handle facebook login/logout in all activities under my tabhost. I have an wrapper for facebook where i handle all my login/logout and posts events. The issue was if I logout from outside of the activity I login from, I will get Invalid Application ID Error and that leads to token not able to reset on the next login.
However I do have a workaround as follow:

Every time I call my wrapper constructor I have the following static softreference for my facebook object.

static SoftReference<Facebook>  fb_ref = null;

Facebook facebook;
public constructor() {
  if(staticVar.facebook == null){
    facebook = new Facebook(<AppID>);
    fb_ref = new SoftReference<Facebook>(facebook);
    facebook = StaticClass.fb_ref;

Android ListView that has RatingBar

If you are using a ratingbar as indicators to number of stars in a custom listview, the ratingbar will take over the onclick event coming into the list. listview.setonitemclickedlistener() will not work in this case.

To overcome this issue, you just need to set the RatingBar attribute the xml file (android:isIndicator=”true”).

Android create option menu with icon

To put an image/icon on your option menu in Android, simply just set something like the below code in your activity

public boolean onCreateOptionsMenu(Menu menu) {
 menu.add(0, Menu.FIRST, 1, "Export").setIcon(R.drawable.music_playqueue_save_playlist);

return super.onCreateOptionsMenu(menu);


Android SMS Receiver

public class SmsReceiver extends BroadcastReceiver {

	private static final String TAG = "AutosendService";
	private static final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private StringBuilder strBuild = new StringBuilder();
	private StringBuilder incomingString = new StringBuilder();

    public void onReceive(Context context, Intent intent) {

            //---get the SMS message passed in---
	    	Bundle bundle = intent.getExtras();

	    	if (bundle != null)
	            //---retrieve the SMS message received---
	            Object[] pdus = (Object[]) bundle.get("pdus");
	            SmsMessage[] msgs = new SmsMessage[pdus.length];
	            for (int i=0; i<msgs.length; i++){
	                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
	                strBuild.append(" : ");

	            Log.i(TAG, "smsReceive: "+strBuild);


 <uses-permission android:name="android.permission.RECEIVE_SMS"/>

<receiver android:name=".SmsReceiver">    
            	<action android:name="android.provider.Telephony.SMS_RECEIVED"/>

Android Camera Intent

private void startCameraIntent() {
		Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		file = new File(<folder>,<filename>);
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(cameraIntent, <CAMERA_REQUEST_CODE>);

Android Facebook SDK post photo

public void postPhotoToFB(){
                Bundle params = new Bundle();
		params.putString("message", <your message>);
		params.putByteArray("picture", <picture byte array>); // check my other blog on how to convert image to byte array
		params.putString("caption", <your caption>);
		fbSyncRunner.request("me/photos", params, "POST",null);

Android getting address from Geocoder

private String getAddress(double currentLatitude, double currentLongitude){
            Geocoder gcd = new Geocoder(context, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(currentLatitude, currentLongitude,100);
            StringBuilder result = new StringBuilder();
            if (addresses.size() > 0) {
                    Address address =  addresses.get(0);
                    int maxIndex = address.getMaxAddressLineIndex();
                    for (int x = 0; x <= maxIndex; x++ ){
            return result.toString();
        catch(IOException ex){
           return null;

Android convert image uri to byte array

public byte[] convertImageToByte(Uri uri){
		byte[] data = null;
		try {
		    ContentResolver cr = getBaseContext().getContentResolver();
		    InputStream inputStream = cr.openInputStream(uri);
		    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		    data = baos.toByteArray();
		} catch (FileNotFoundException e) {
		return data;