Blog

  • How to make Android CheckBox and RadioButton custom style

    How to make Android CheckBox and RadioButton custom style

    Hi,

    Anybody know that real cool Android application must have not only excelent business logic. The one of the most important things what application must have is a nice UI.

    If you want to create realy interesting application you need to create good UI. And …. hire a designer 🙂

    Below i want to tell you how to create your own CheckBoxes and RadioButtons for your Android Applications. Sorry for this sample UI design. I didn’t hire a designer :).

    First look at screenshot:

    Here you can see simple app with only one activity. Also below you can download the source code of Android project.

    To make your own style for CheckBox or RadioButton you need to do next:

    • Create Image Drawables for their two stater (checked/unchecked)
    • Create selector for this two drawables. The sample content must be seem like this:
    <?xml version="1.0" encoding="utf-8">
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:drawable="@drawable/star_down"></item>
        <item android:state_checked="false" android:drawable="@drawable/star"></item>
    </selector>
    • Add this selector as android:button attribute for CheckBox or RadioButton
    <CheckBox android:text="Custom CheckBox" 
        android:button="@drawable/checkbox_selector" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content">

    That’s all. To make custom style for CheckBox and RadioButton you must do same steps.
    Here you can download the Android project with the sample.

    Download it from github
  • How to make custom indeterminate ProgressBar in Android or how to change ProgressBar style or color

    How to make custom indeterminate ProgressBar in Android or how to change ProgressBar style or color

    Hi,

    Here i want to show you how easily make your own Android ProgressBar style or how to change ProgressBar color.

    It is very easy! Also below you can download source code of Android project.

    Below you can see the screenShot with ProgressBar

    Indeterminate ProgressBar style

    To do this you need:

    • Create the image for this ProgressBar in any graphical editor.
    • Create animation drawable with content:
    <?xml version="1.0" encoding="utf-8"?>
    <animated-rotate 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        android:drawable="@drawable/image_for_rotation" 
        android:pivotX="50%"
    	android:pivotY="50%" />

    Where @drawable/image_for_rotation is the resource of your progressBar image.

    Select android:indeterminateDrawable for ProgressBar witget.

    <?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"
        android:gravity="center">
        <ProgressBar android:indeterminateDrawable="@drawable/my_progress_indeterminate" android:layout_height="100dp" android:layout_width="100dp"></ProgressBar>
    </LinearLayout>

    Enjoy! 🙂

    Here you can download Sample project with custom Android ProgressBar.

    Download it from github
  • Sample streaming video mediaplayer or how to stream video from url in Android.

    Sample streaming video mediaplayer or how to stream video from url in Android.

    Hi,

    I want to share you my sample Android video player. This player can play video from URL. Also below you can download source code of Android Maven project.

    My player have individual style. What features does the player have:

    • Nice MediaController. I don’t use MediaController from Android API.
    • New SeekBar style
    • Animation for MedeaController. If user don’t touch screen for the 5 seconds then MediaController slow disapears.
    • Pause playing by click the screen. (Like youtube Android application).

    This mediaplayer is not perfect, but it is very good tutorial for newbies. Enjoy!

    Here you can see the video:

    Download it from github
  • Inserting youtube video in forum’s post by URL. Youtube BBCode.

    Inserting youtube video in forum’s post by URL. Youtube BBCode.

    Hello,

    Yesterday i needed BBCode which inserting Youtube.com video by URL, not by video ID. I don’t found this 🙂

    Here i show you my BBCode.

    BBCode usage:

    [youtube]{URL}[/youtube]

    HTML Replacement:

    <script type="text/javascript">
        var s = '{URL}';
        var s2 = s.split("?v=")[1].split("&")[0];
        document.write('<iframe width="425" height="350" src="https://www.youtube.com/embed/' + s2 +'?rel=0" frameborder="0" allowfullscreen></iframe>');
    </script>
  • How to run Android application then you use Maven in your project

    How to run Android application then you use Maven in your project

    Then i first tried use Maven in my Android projects i have some discomfort then run my applications with

    mvn clean install android:deploy

    and then all is successful i can see my app bringing to front of my device which i can see then run standard Android apps with Run As..–>Android Aplication in Eclipse.

    This instruction will works only in Linux. If you use Windows you need to rewrite some scripts according to your OS shell script language

    I find some solution of this little problem.
    First you need Exec Maven Plugin existing in your pom.xml

    <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <configuration>
            <executable>${basedir}/scripts/run_app.sh</executable>
        </configuration>
    </plugin>

    Next create scripts dir in your project. That dir  need to heve run_app.sh bash file with next content:

    adb shell am start -a android.intent.action.MAIN -n your.app.package/.YourMainActivity

    Go to scripts dir in your terminal and make this file executable by all with

    sudo chmod '777' run_app.sh

    That all. Next you need to execute next in your terminal then located in project root dir (same level as pom.xml)

    mvn clean install android:deploy; mvn exec:exec

    Hope it will useful for you

    Project you can download below.
    Just untar and import as Existing Maven Project in your Eclipse.

    Download it from github
  • Google Chrome browser hangs on Linux Ubuntu 10.04 Lucid Lynx. How fix this

    Google Chrome browser hangs on Linux Ubuntu 10.04 Lucid Lynx. How fix this

    May be you know this problem. Some times if you try to save some web content to your computer the Chrome browser hangs and you can’t do anything else.

    Recently i accidentally found how to quickly back your Chrome browser to life without killing the chrome process.

    Its do by simple press Print Screen key on your keyboard. Thats all.

    If you are MacBook user you may not found Print Screen key on MacBook keyboard.
    In this case you must create keyboard shortcut with this function.
    To do this please select System > Preferences > Keyboard Shortcuts and in this dialog set the shortcut for Take a screenshot menu position.

    Have fun 🙂

  • Android GPS Using. How to get current location example

    Android GPS Using. How to get current location example

    Hi. Here i want show you how to use Android GPS quickly. This is simple, may be not perfect example how to get current location by GPS.
    To use GPS in your application first of all you must specify the uses-permission in Android manifest file:

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

    If you don’t set this permission the application can’t get access to location service.

    To use this application with android emulator you must mock location data. To do this using Eclipse you must:

    • Select Window > Show View > Other > Emulator Control
    • In Emulator Control panel enter the GPS coordinates under Location Controls and press Send

    This operation you must do every time then you Run application.

    Below you can see the application activity (HelloAndroidGpsActivity.java) source. Below you can download the source code of this Android project.
    For more information about Android GPS Usage look HERE

    package com.hrupin;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.AlertDialog.Builder;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    
    public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
    
    	private EditText editTextShowLocation;
    	private Button buttonGetLocation;
    	private ProgressBar progress;
    
    	private LocationManager locManager;
    	private LocationListener locListener = new MyLocationListener();
    
    	private boolean gps_enabled = false;
    	private boolean network_enabled = false;
    
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
    
    		progress = (ProgressBar) findViewById(R.id.progressBar1);
    		progress.setVisibility(View.GONE);
    
    		buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
    		buttonGetLocation.setOnClickListener(this);
    
    		locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    	}
    
    	@Override
    	public void onClick(View v) {
    		progress.setVisibility(View.VISIBLE);
    		// exceptions will be thrown if provider is not permitted.
    		try {
    			gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    		} catch (Exception ex) {
    		}
    		try {
    			network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    		} catch (Exception ex) {
    		}
    
    		// don't start listeners if no provider is enabled
    		if (!gps_enabled &amp;amp;amp;amp;&amp;amp;amp;amp; !network_enabled) {
    			AlertDialog.Builder builder = new Builder(this);
    			builder.setTitle("Attention!");
    			builder.setMessage("Sorry, location is not determined. Please enable location providers");
    			builder.setPositiveButton("OK", this);
    			builder.setNeutralButton("Cancel", this);
    			builder.create().show();
    			progress.setVisibility(View.GONE);
    		}
    
    		if (gps_enabled) {
    			locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
    		}
    		if (network_enabled) {
    			locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
    		}
    	}
    
    	class MyLocationListener implements LocationListener {
    		@Override
    		public void onLocationChanged(Location location) {
    			if (location != null) {
    				// This needs to stop getting the location data and save the battery power.
    				locManager.removeUpdates(locListener); 
    
    				String londitude = "Londitude: " + location.getLongitude();
    				String latitude = "Latitude: " + location.getLatitude();
    				String altitiude = "Altitiude: " + location.getAltitude();
    				String accuracy = "Accuracy: " + location.getAccuracy();
    				String time = "Time: " + location.getTime();
    
    				editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
    				progress.setVisibility(View.GONE);
    			} 
    		}
    
    		@Override
    		public void onProviderDisabled(String provider) {
    			// TODO Auto-generated method stub
    
    		}
    
    		@Override
    		public void onProviderEnabled(String provider) {
    			// TODO Auto-generated method stub
    
    		}
    
    		@Override
    		public void onStatusChanged(String provider, int status, Bundle extras) {
    			// TODO Auto-generated method stub
    
    		}
    	}
    
    	@Override
    	public void onClick(DialogInterface dialog, int which) {
    		if(which == DialogInterface.BUTTON_NEUTRAL){
    			editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
    		}else if (which == DialogInterface.BUTTON_POSITIVE) {
    			startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
    		}
    	}
    
    }

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

    Download it from github
  • Example of streaming mp3 mediafile from URL with Android MediaPlayer class

    Example of streaming mp3 mediafile from URL with Android MediaPlayer class

    Few days ago i tried to make my Android app can play music from URL.

    The Android API give to us a very useful class. Here i want show you how to make  the streaming m3 mediaplayer using MediaPlayer class from Android API. This app use Android 2.2.

    Below you can see the UI of this app. It’s very simple. Also below you can get the link for downloading source code

    Here i show you only Activity file (StreamingMp3Player.java).

    package com.hrupin.streamingmedia;
    
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.media.MediaPlayer.OnBufferingUpdateListener;
    import android.media.MediaPlayer.OnCompletionListener;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.View.OnTouchListener;
    import android.widget.EditText;
    import android.widget.ImageButton;
    import android.widget.SeekBar;
    
    import com.hrupin.media.R;
    
    public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
    	
    	private ImageButton buttonPlayPause;
    	private SeekBar seekBarProgress;
    	public EditText editTextSongURL;
    	
    	private MediaPlayer mediaPlayer;
    	private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
    	
    	private final Handler handler = new Handler();
    	
    	/** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            initView();
        }
        
        /** This method initialise all the views in project*/
        private void initView() {
    		buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
    		buttonPlayPause.setOnClickListener(this);
    		
    		seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);	
    		seekBarProgress.setMax(99); // It means 100% .0-99
    		seekBarProgress.setOnTouchListener(this);
    		editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
    		editTextSongURL.setText(R.string.testsong_20_sec);
    		
    		mediaPlayer = new MediaPlayer();
    		mediaPlayer.setOnBufferingUpdateListener(this);
    		mediaPlayer.setOnCompletionListener(this);
    	}
    
    	/** Method which updates the SeekBar primary progress by current song playing position*/
        private void primarySeekBarProgressUpdater() {
        	seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
    		if (mediaPlayer.isPlaying()) {
    			Runnable notification = new Runnable() {
    		        public void run() {
    		        	primarySeekBarProgressUpdater();
    				}
    		    };
    		    handler.postDelayed(notification,1000);
        	}
        }
    
    	@Override
    	public void onClick(View v) {
    		if(v.getId() == R.id.ButtonTestPlayPause){
    			 /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
    			try {
    				mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from https://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
    				mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer. 
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    			
    			mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
    			
    			if(!mediaPlayer.isPlaying()){
    				mediaPlayer.start();
    				buttonPlayPause.setImageResource(R.drawable.button_pause);
    			}else {
    				mediaPlayer.pause();
    				buttonPlayPause.setImageResource(R.drawable.button_play);
    			}
    			
    			primarySeekBarProgressUpdater();
    		}
    	}
    
    	@Override
    	public boolean onTouch(View v, MotionEvent event) {
    		if(v.getId() == R.id.SeekBarTestPlay){
    			/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
    			if(mediaPlayer.isPlaying()){
    		    	SeekBar sb = (SeekBar)v;
    				int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
    				mediaPlayer.seekTo(playPositionInMillisecconds);
    			}
    		}
    		return false;
    	}
    
    	@Override
    	public void onCompletion(MediaPlayer mp) {
    		 /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
    		buttonPlayPause.setImageResource(R.drawable.button_play);
    	}
    
    	@Override
    	public void onBufferingUpdate(MediaPlayer mp, int percent) {
    		/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
    		seekBarProgress.setSecondaryProgress(percent);
    	}
    }
    

    I hope it will be useful for you.

    Please download if you want to see some other file from this Android project.

    Download it from github
  • How to create VirtualHost in Linux Ubuntu 10.04 Lucid Lynx

    How to create VirtualHost in Linux Ubuntu 10.04 Lucid Lynx

    The procedure of creation VirtualHost in Linux is very simple.
    I try to make it more simple for me. The result of this work is .sh script that you can download below. Just untar this archive

    tar xvf vhosts.sh.tar.gz

    and run this script in terminal with sudo.
    Example of usage:

    IP = 127.0.0.1
    ServerName = example.com
    ServerAdmin email = webmaster@example.com
    Your username in System = user
    htdocs directory path = /home/user/htdocs/

    If we located in same directory that vhosts.sh script command in terminal will be:

    sudo ./vhosts.sh 127.0.0.1 example.com webmaster@example.com user /home/user/htdocs/

    Now open your browser and type the adress http://example.com .If allright you will see phpinfo();
    hope it’s will be useful for you.

    For more tutorial information look in script file.

    Download it from github
  • Simple Android mp3 media player example

    Simple Android mp3 media player example

    Here i want to write about my first experience in Android Dev.
    This application just play embedded in application mp3 file. That’s all.
    Below you can download the source code.
    In first step i create a simple Android UI. Below you can see this:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    android:id="@+id/widget31"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
        <Button
            android:text="@string/play_str"
            android:textSize="15pt"
            android:textStyle="bold"
            android:id="@+id/ButtonPlayStop"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
        <SeekBar
            android:id="@+id/SeekBar01"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_below="@id/ButtonPlayStop"/>
    </RelativeLayout>

    In my simple mp3 media player i have few string constans, like “PLAY”, “PAUSE”, etc. The best practice is place this constats in special part of project. That part call values. In this part i Eclipse create for me strings.xml file and change it. Bellow you can see strings.xml content:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="app_name">Android mp3 player</string>
        <string name="play_str">PLAY</string>
        <string name="pause_str">PAUSE</string>
    </resources>

    It’s very simple and useful practice.

    Next i make changes in Activity file (Mp3player.java). Bellow i give you some comments about it:

    package com.hrupin.mp3player;
    
    import com.hrupin.mp3player.R;
    
    import android.app.Activity;
    import android.media.MediaPlayer;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.MotionEvent;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.View.OnTouchListener;
    import android.widget.Button;
    import android.widget.SeekBar;
    
    public class Mp3player extends Activity {
    
        private Button buttonPlayStop;
        private MediaPlayer mediaPlayer;
        private SeekBar seekBar;
    
        private final Handler handler = new Handler();
    
        // Here i override onCreate method.
        //
        // setContentView() method set the layout that you will see then
        // the application will starts
        //
        // initViews() method i create to init views components.
        @Override
        public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                setContentView(R.layout.main);
                initViews();  
    
        }
    
        // This method set the setOnClickListener and method for it (buttonClick())
        private void initViews() {
            buttonPlayStop = (Button) findViewById(R.id.ButtonPlayStop);
            buttonPlayStop.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {buttonClick();}});
    
            mediaPlayer = MediaPlayer.create(this, R.raw.testsong_20_sec); 
    
            seekBar = (SeekBar) findViewById(R.id.SeekBar01);
            seekBar.setMax(mediaPlayer.getDuration());
            seekBar.setOnTouchListener(new OnTouchListener() {@Override public boolean onTouch(View v, MotionEvent event) {
            	seekChange(v);
    			return false; }
    		});
    
        }
    
        public void startPlayProgressUpdater() {
        	seekBar.setProgress(mediaPlayer.getCurrentPosition());
    
    		if (mediaPlayer.isPlaying()) {
    			Runnable notification = new Runnable() {
    		        public void run() {
    		        	startPlayProgressUpdater();
    				}
    		    };
    		    handler.postDelayed(notification,1000);
        	}else{
        		mediaPlayer.pause();
        		buttonPlayStop.setText(getString(R.string.play_str));
        		seekBar.setProgress(0);
        	}
        } 
    
        // This is event handler thumb moving event
        private void seekChange(View v){
        	if(mediaPlayer.isPlaying()){
    	    	SeekBar sb = (SeekBar)v;
    			mediaPlayer.seekTo(sb.getProgress());
    		}
        }
    
        // This is event handler for buttonClick event
        private void buttonClick(){
            if (buttonPlayStop.getText() == getString(R.string.play_str)) {
                buttonPlayStop.setText(getString(R.string.pause_str));
                try{
                	mediaPlayer.start();
                    startPlayProgressUpdater();
                }catch (IllegalStateException e) {
                	mediaPlayer.pause();
                }
            }else {
                buttonPlayStop.setText(getString(R.string.play_str));
                mediaPlayer.pause();
            }
        }
    }
    Download it from github