Blog

  • How to use Xeger lib with maven

    How to use Xeger lib with maven

    It will be useful for you if you need to get text which can be match with your existing regular expression in JAVA.

    Recently a had same question. I use Xeger (http://code.google.com/p/xeger/).

    First of all you need to download JAR from http://code.google.com/p/xeger/.

    Next you need to run in command line next command:

    mvn install:install-file -Dfile=~/Downloads/xeger-1.0-SNAPSHOT.jar -DgroupId=nl.flotsam -DartifactId=xeger -Dversion=1.0-SNAPSHOT -Dpackaging=jar

    There is linux-path to JAR file (~/Downloads/xeger-1.0-SNAPSHOT.jar). groupId, artifactId, version …. for xeger-1.0-SNAPSHOT.jar file. If you use another you need make some changes in command.

    Next you need to copy JAR file in to .m2/repository/nl/flotsam/xeger/1.0-SNAPSHOT dir

    in order to use Xeger you need also install in maven repository the dk.brics.automaton package.

    Here part of my pom.xml:

    <dependency>
        <groupid>nl.flotsam</groupid>
        <artifactid>xeger</artifactid>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupid>dk.brics</groupid>
        <artifactid>automaton</artifactid>
        <version>1.11</version>
    </dependency>

    If you have some questions you can create a comment for this post.

    Have a nice codding!

  • How to put some special math symbols in TextView, EditView or other Android UI element.

    How to put some special math symbols in TextView, EditView or other Android UI element.

    Here the screenshot with special math symbols

    To make this you need just put HTML codes of with this symbols in TextView or other Android widget. Here the code:

    String htmlStringWithMathSymbols = "&#8722;   &#43;   &#177;   &#215;   &#247;   &#37;   &#137;   &#61;   &#8800;   &#8776;   &#8801;   &#60;   &#62;   &#8804;   &#8805;   &#8734;   &#8539;   &#188;   &#8540;   &#189;   &#8541;   &#190;   &#8542;   &#8747;   &#8706;   &#8710;   &#8719;   &#8721;   &#8730;   &#8735;   &#8745;   &#8729;   &#131;   &#8260;   ";
    
    textView.setText(Html.fromHtml(htmlStringWithMathSymbols));
  • How to centering google map on Balloon center in Android

    How to centering google map on Balloon center in Android

    If you click (tap) the balloon on Android Google Maps in your application, and want to centering map on center of balloon. You need to look this post.

    Below you can download the source code of sample Android project.

    The secret in Utils class. Below you can see the source of this class

    package com.hrupin.lazymarkers;
    
    import android.content.Context;
    import android.util.DisplayMetrics;
    
    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapView;
    
    public class Utils {
        private static final int BALLOON_OFFSET_IN_DP = 150;
        private static final double EQUATRE_LENGTH_IN_KM = 40075.7;
        private static final double EARTH_RADIUS_IN_KM = 6356.8;
        private static DisplayMetrics metrics = null;
        private static float density;
    
        public static GeoPoint getBalloonCenterCoords(GeoPoint markerGeoPoint, MapView mapView) {
            int zoom = mapView.getZoomLevel();
            int balloonOffset = getOffsetInDegreesE6(zoom, dpToPxConverter(mapView.getContext(), BALLOON_OFFSET_IN_DP));
            int balloonCenterLatitude = markerGeoPoint.getLatitudeE6() + balloonOffset;
            return new GeoPoint(balloonCenterLatitude, markerGeoPoint.getLongitudeE6());
        }
    
        private static int getOffsetInDegreesE6(int zoom, int offsetInPx) {
            // 256 - equator length on map if zoom level = 0
            double equatreLengthOnMapInPx = (double) 256 * Math.pow(2, zoom);
            double earthRadiusOnMapInPx = (equatreLengthOnMapInPx * EARTH_RADIUS_IN_KM) / EQUATRE_LENGTH_IN_KM;
            double tangensValue = (double) offsetInPx / earthRadiusOnMapInPx;
            double offsetInDegrees = Math.toDegrees(Math.atan(tangensValue));
            return (int) (offsetInDegrees * 1E6);
        }
    
        private static int dpToPxConverter(Context context, int dp) {
            if (metrics == null) {
                metrics = context.getResources().getDisplayMetrics();
                density = metrics.density;
            }
            return (int) (density * dp + 0.5f);
        }
    }

    Please tell me if you know other solution.

    Hope it help you!

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

    Download it from github
  • How to Clear User Data in your Android Application programmatically

    How to Clear User Data in your Android Application programmatically

    How to clear user data of your application programmatically? Here I share with you my solution how to do this.

    You also can clear your user data by clicking “Clear Data” button in Settings–>Applications–>Manage Aplications–> YOUR APPLICATION

    To do it programmatically you need to remove user data from application dir.

    Below you can download source code of sample Android project.

    Pay attention in MyApplication class:

    package com.hrupin.cleaner;
    
    import java.io.File;
    
    import android.app.Application;
    import android.util.Log;
    
    public class MyApplication extends Application {
    	private static MyApplication instance;
    
    	@Override
    	public void onCreate() {
    		super.onCreate();
    		instance = this;
    	}
    	
    	public static MyApplication getInstance(){
    		return instance;
    	}
    	
    	public void clearApplicationData() {
    		File cache = getCacheDir();
    		File appDir = new File(cache.getParent());
    		if(appDir.exists()){
    			String[] children = appDir.list();
    			for(String s : children){
    				if(!s.equals("lib")){
    					deleteDir(new File(appDir, s));
    					Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
    				}
    			}
    		}
    	}
    	
    	public static boolean deleteDir(File dir) {
    	    if (dir != null && dir.isDirectory()) {
    	        String[] children = dir.list();
    	        for (int i = 0; i < children.length; i++) {
    	            boolean success = deleteDir(new File(dir, children[i]));
    	            if (!success) {
    	                return false;
    	            }
    	        }
    	    }
    
    	    return dir.delete();
    	}
    }
    Download it from github
  • How to include Facebook Android SDK in project as maven module

    How to include Facebook Android SDK in project as maven module

    This post will be usefull if you have Android maven multimodule project and want to include Facebook Android SDK  in your project as module.

    How do this?

    As you see here https://github.com/facebook/facebook-android-sdk the Facebook SDK used not as maven module.

    Below you can download source code of Android project

    To do this you need:

    1. Download the Facebook Android SDK from github.

    2. Add Facebook Android SDK lib project in your workspace near other modules of your maven project. Look at screenshot below:

    3. Ensure that your facebook dir contauns next files and dirs. Look at screenshot below:

    4. Add to parent project’s pom.xml new module. The block may look like this:

    <modules>
        <module>facebook</module>
        <module>application</module>
    </modules>

    5. Add in to facebook dir next pom.xml file. Don’t forget setup group_id, artifact_id and version of your parent project. I noticed in code where you need to do this:

    <project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelversion>4.0.0</modelversion>
    </project>
    
    <parent> 
        <groupid>YOUR_PARENT_PROJECT_GROUP_ID</groupid>
        <artifactid>YOUR_PARENT_PROJECT_ARTIFACT_ID</artifactid>
        <version>YOUR_PARENT_PROJECT_VERSION</version> 
    </parent>
    
    <groupid>com.facebook.android</groupid>
    <artifactid>facebook-android-sdk</artifactid>
    <version>0.0.1</version> 
    <packaging>jar</packaging> 
    <name>Facebook Android SDK</name>
    
    <dependencies>
        <dependency>
            <groupid>com.google.android</groupid>
            <artifactid>android</artifactid>
        </dependency>
    </dependencies>
    <build> 
        <plugins> 
            <plugin> 
                <groupid>com.jayway.maven.plugins.android.generation2</groupid>
                <artifactid>maven-android-plugin</artifactid>
                <configuration>
                    <androidmanifestfile>${project.basedir}/AndroidManifest.xml
                    </androidmanifestfile>
                    <assetsdirectory>${project.basedir}/assets</assetsdirectory>
                    <resourcedirectory>${project.basedir}/res</resourcedirectory>
                    <nativelibrariesdirectory>${project.basedir}/src/main/native
                    </nativelibrariesdirectory>
                    <sdk> 
                        <platform>8</platform> 
                    </sdk>
                    <deleteconflictingfiles>true</deleteconflictingfiles>
                    <undeploybeforedeploy>true</undeploybeforedeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin> 
            <plugin> 
                <artifactid>maven-compiler-plugin</artifactid>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    6. Change path to java source files from src/com/facebook/android to src/main/java/com/facebook/android

    7. Delete all projects from your Eclipse’s package explorer.

    8. Import project as Maven project. If you do it right you can see next:

    When you import this project the Eclipse will create target dir in your facebook project with APK file.

    8. Add Facebook Android SDK dependencies in your application. To do this open pom.xml of your app and add next code in <dependencies>.

    <dependency>
        <groupid>com.facebook.android</groupid>
        <artifactid>facebook-android-sdk</artifactid>
        <version>0.0.1</version>
    </dependency>

    And whole pom.xml of your app need to be looks like this:

    <?xml version="1.0" encoding="UTF-8"?> 
    <project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelversion>4.0.0</modelversion>
    </project>
    
    <parent> 
        <groupid>YOUR_PARENT_PROJECT_GROUP_ID</groupid>
        <artifactid>YOUR_PARENT_PROJECT_ARTIFACT_ID</artifactid>
        <version>YOUR_PARENT_PROJECT_VERSION</version> 
    </parent>
    
    <groupid>com.hrupin</groupid>
    <artifactid>facebook-android-maven-sample</artifactid>
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>apk</packaging> 
    <name>facebook-android-maven-sample - Application</name>
    
    <dependencies>
        <dependency>
            <groupid>com.google.android</groupid>
            <artifactid>android</artifactid>
        </dependency>
        <dependency>
            <groupid>com.facebook.android</groupid>
            <artifactid>facebook-android-sdk</artifactid>
            <version>0.0.1</version>
        </dependency>
    </dependencies>
    <build> 
        <plugins> 
            <plugin> 
            <groupid>com.jayway.maven.plugins.android.generation2</groupid>
                <artifactid>maven-android-plugin</artifactid>
                <configuration>
                    <androidmanifestfile>${project.basedir}/AndroidManifest.xml</androidmanifestfile>
                    <assetsdirectory>${project.basedir}/assets</assetsdirectory>
                    <resourcedirectory>${project.basedir}/res</resourcedirectory>
                    <nativelibrariesdirectory>${project.basedir}/src/main/native</nativelibrariesdirectory>
                    <sdk> 
                        <platform>8</platform>
                    </sdk>
                    <deleteconflictingfiles>true</deleteconflictingfiles>
                    <undeploybeforedeploy>true</undeploybeforedeploy>
                </configuration>
                <extensions>true</extensions> 
            </plugin> 
            <plugin> 
                <artifactid>maven-compiler-plugin</artifactid>
                <configuration>
                    <source />1.6
                    <target>1.6</target>
                </configuration> 
            </plugin> 
        </plugins> 
    </build>

    That’s all. Try to build your project with maven:

    cd your_parent_project_dir
    mvn clean install

    This sample is not detailed. If you have some troubles you can leave me comment and i will try to ask you.

    Hope, it help you!
    Here you can download sample project with Facebook Android SDK as maven module

    Download it from github
  • 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