Month: October 2011

  • How to implement lazy loading for markers on Google Maps in Android.

    How to implement lazy loading for markers on Google Maps in Android.

    If your objects which you want to show on the Google Maps in Android have different markers. You need to use lazy loading for markers.

    How to do it? It’s very easy. Just use AsyncTask . 

    Below you can download source code of Android project.

    When you start application you can see Google Maps with red default markers. When custom marker loaded the custom marker will replace default marker and update map overlay.

    To see map you need specify your own Google Maps API Key in MapView  (see main.xml file)

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="vertical"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent">
    	<com.google.android.maps.MapView android:id="@+id/mapView" android:layout_width="fill_parent" android:layout_height="fill_parent"
    		android:clickable="true" android:apiKey="YOUR_API_KEY" />
    </LinearLayout>

    Other info you can see in the code. It is simple to understand. Please, add the questions in comments.

    Here code of the AsyncTask class

    package com.hrupin.lazymarkers;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URI;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.entity.BufferedHttpEntity;
    import org.apache.http.impl.client.DefaultHttpClient;
    
    import com.google.android.maps.MapView;
    import com.google.android.maps.OverlayItem;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.os.AsyncTask;
    
    public class MapOverlayItemMarkerAsyncTask extends AsyncTask<String, Void, Bitmap> {
    
    	private OverlayItem overlayitem;
    	private MapView mapView;
    
    	public MapOverlayItemMarkerAsyncTask(OverlayItem overlayitem, MapView mapView) {
    		this.overlayitem = overlayitem;	
    		this.mapView = mapView;
    	}
    	
    	@Override
    	protected Bitmap doInBackground(String... params) {		
    		Bitmap bitmap = null;
    		InputStream in = null;
    		try {
    			in = fetch(params[0]);
    			bitmap = BitmapFactory.decodeStream(in, null, null);
    			in.close();
    			return bitmap;
    		} catch (IOException e1) {
    			return null;
    		} 
    	}
    
    	private static InputStream fetch(String address) throws MalformedURLException,IOException {
    	    HttpGet httpRequest = new HttpGet(URI.create(address) );
    	    HttpClient httpclient = new DefaultHttpClient();
    	    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    	    HttpEntity entity = response.getEntity();
    	    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    	    InputStream instream = bufHttpEntity.getContent();
    	    return instream;
    	}
    
    	@Override
    	protected void onPostExecute(Bitmap result) {
    		if (result != null) {
    			Drawable drawable = new BitmapDrawable(result);
    			drawable.setBounds(-drawable.getIntrinsicWidth() / 2, -drawable.getIntrinsicHeight(), drawable.getIntrinsicWidth() / 2, 0);
    			overlayitem.setMarker(drawable);
    			mapView.invalidate();
    		}
    	}
    	
    }

    Here you can download the source code of the Android project.

    Download it from github
  • How to set the different screen orientations for TabActivity children activities

    How to set the different screen orientations for TabActivity children activities

    Hi,
    Here I want to show you how to make different screen orientation for TabActivity children activities.

    You may say “Just specify this in Android Manifest file. That’s All”. But, it didn’t works. All child activities have same orientation with parent (TabActivity).

    Below you can download source code of Android project

    I will show you how I fix this for me.

    1. Specify the portrait or some else orientation for TabActivity in Manifest file. This will be default orientation for all child activities.
    2. Save reference to TabActivity as static field in TabActivity class
    3. Download the source code below. Pay attantion in onPause and onResume methods in SecondTabActivity class.
    <div>The code is so simple :)</div>

    TabActivitySampleActivity.java

    package com.hrupin;
    
    import android.app.TabActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.widget.TabHost;
    import android.widget.TabHost.TabSpec;
    
    public class TabActivitySampleActivity extends TabActivity {
    	
    	private static TabActivitySampleActivity INSTANCE;
    	
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            INSTANCE = this;
            TabHost host = getTabHost();
            
            TabSpec tab1 = host.newTabSpec("tab1");
            tab1.setIndicator("TAB 1");
            tab1.setContent(new Intent(this, FirstTabActivity.class));
            
            TabSpec tab2 = host.newTabSpec("tab2");
            tab2.setIndicator("TAB 2");
            tab2.setContent(new Intent(this, SecondTabActivity.class));
            
            host.addTab(tab1);
            host.addTab(tab2);
        }
        
        public static TabActivitySampleActivity getInstance(){
        	return INSTANCE;
        }
    }

    FirstTabActivity.java

    package com.hrupin;
    
    import android.app.Activity;
    import android.os.Bundle;
    
    public class FirstTabActivity extends Activity {
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.first);
    	}
    }

    SecondTabActivity.java

    package com.hrupin;
    
    import android.app.Activity;
    import android.content.pm.ActivityInfo;
    import android.os.Bundle;
    
    public class SecondTabActivity extends Activity {
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.second);
    	}
    	
    	@Override
    	protected void onResume() {
    		super.onResume();
    		TabActivitySampleActivity.getInstance().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    	}
    	
    	@Override
    	protected void onPause() {
    		super.onPause();
    		TabActivitySampleActivity.getInstance().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	}
    }

    Here  you can download the source code of Android project

    Download it from github
  • How to scroll ListView to top or other position

    How to scroll ListView to top or other position

    Hi,
    Recently I want to scroll my ListView widget in my application to top.

    Below you can download source code of Android project

    To do this I made simple call:

    int n = 0 // listView desire position.
    listView.smoothScrollToPosition(n);

    That’s all 🙂 .This code working since Android 8 API or Android 2.2

    Download it from github
  • How to implement slow popup showing in Android. Or simple Animation sample.

    How to implement slow popup showing in Android. Or simple Animation sample.

    Anybody know that cool Android animation need to be smooth.
    For example. Your application need to show some popup with mediaplayer controls (play/pause buttons, etc….). How to implement this?

    Below you can download source code of Android project

    I will show you how I implemented this in one of my projects. Below you can see youtube video:

    The activity’s source code is here:

    package com.hrupin;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.animation.Animation;
    import android.view.animation.AnimationUtils;
    import android.view.animation.Animation.AnimationListener;
    import android.widget.Button;
    import android.widget.LinearLayout;
    
    public class SampleActivity extends Activity implements OnClickListener, AnimationListener {
    	/** Called when the activity is first created. */
    
    	private Animation popupShow;
    	private Animation popupHide;
    
    	private LinearLayout linearLayoutPopup;
    	private Button buttonShowHidePopup;
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    
    		popupShow = AnimationUtils.loadAnimation(this, R.anim.popup_show);
    		popupShow.setAnimationListener(this);
    		popupHide = AnimationUtils.loadAnimation(this, R.anim.popup_hide);
    		popupHide.setAnimationListener(this);
    
    		linearLayoutPopup = (LinearLayout) findViewById(R.id.linearLayoutPopUp);
    		linearLayoutPopup.setVisibility(View.GONE);
    
    		buttonShowHidePopup = (Button) findViewById(R.id.buttonShowHidePopUp);
    		buttonShowHidePopup.setOnClickListener(this);
    	}
    
    	@Override
    	public void onClick(View v) {
    		if (linearLayoutPopup.getVisibility() == View.GONE) {
    			linearLayoutPopup.startAnimation(popupShow);
    		} else {
    			linearLayoutPopup.startAnimation(popupHide);
    		}
    	}
    
    	@Override
    	public void onAnimationEnd(Animation animation) {
    		if (animation.equals(popupShow)) {
    			buttonShowHidePopup.setText(getString(R.string.btn_hide_txt));
    		} else if (animation.equals(popupHide)) {
    			buttonShowHidePopup.setText(getString(R.string.btn_show_txt));
    		}
    	}
    
    	@Override
    	public void onAnimationRepeat(Animation animation) {
    		// TODO Auto-generated method stub
    
    	}
    
    	@Override
    	public void onAnimationStart(Animation animation) {
    		if (animation.equals(popupShow)) {
    			linearLayoutPopup.setVisibility(View.VISIBLE);
    		} else if (animation.equals(popupHide)) {
    			linearLayoutPopup.setVisibility(View.GONE);
    		}
    	}
    }

    The code is pretty simple 🙂

    You can download the source code from github

    Download it from github
  • How to finish all activities in your Android application through simple call

    How to finish all activities in your Android application through simple call

    Hi,

    Maybe you had some problem which i can discribe and show the way to fix it.

    Actually, problem is a closing all your Android application’s Activities through simple call.

    There are many ways to fix this. I want to show you one of them.

    Before starting i want to ask you something. Please email me or post a comment for this post if you find better and more flexible way to close all Android application’s activities. I will be appreciative you!!

    Below you can download the sample project. This project contains 3 (three) activities and ONE abstract Activity. All Activities in this sample project extended this abstract Activity class. This Activity extended Activity class from Android API.

    The most interesting contains in this abstract Activity. Here the source:

    package com.hrupin;
    
    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    
    public abstract class AppBaseActivity extends Activity {
    	public static final String FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION = "com.hrupin.FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION";
    	private BaseActivityReceiver baseActivityReceiver = new BaseActivityReceiver();
    	public static final IntentFilter INTENT_FILTER = createIntentFilter();
    	
    	private static IntentFilter createIntentFilter(){
    		IntentFilter filter = new IntentFilter();
    		filter.addAction(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION);
    		return filter;
    	}
    	
    	protected void registerBaseActivityReceiver() {
    		registerReceiver(baseActivityReceiver, INTENT_FILTER);
    	}
    	
    	protected void unRegisterBaseActivityReceiver() {
    		unregisterReceiver(baseActivityReceiver);
    	}
    	
    	public class BaseActivityReceiver extends BroadcastReceiver{
    		@Override
    		public void onReceive(Context context, Intent intent) {
    			if(intent.getAction().equals(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION)){
    				finish();
    			}
    		}
    	} 
    	
    	protected void closeAllActivities(){
    		sendBroadcast(new Intent(FINISH_ALL_ACTIVITIES_ACTIVITY_ACTION));
    	}
    }

    You can see that this class contains BrodcastReceiver –> BaseActivityReceiver

    This broadcastReceiver makes finish() Activity. This class also contains methods to create intentFilter, register/unregister broadcastReceiver and method closeAllActivities() which broadcast Intent to close Activities of only YOUR Android apllication.

    The code is pretty simple. 🙂
    Here you can download the sample project

    Download it from github