Sunday 29 December 2013

ProgressFragment

Implementation of the fragment with the ability to display indeterminate progress indicator when you are waiting for the initial data. Based on ListFragment.


Download from GitHub

ExtendedCalendarView

This project is meant for people who want to display a calendar view and show that there are events on certain days. What I did was pull out the calendar view from Google’s Calendar application.
Implementation is not the easiest though as there is a lot to it but I hope to filter out stuff that is not needed to try to make it simpler.


Download from GitHub

ProgressButton

ProgressButton is a custom progress indicator with a tiny footprint. Based on the sample code provided by Roman Nurik on Google Code. The default implementation provides a pin progress button as seen on the Android design site.
The color indicates whether it’s downloaded (blue) or not (gray). The appearance of the pin indicates whether the download is permanent (white, upright) or temporary (gray, diagonal). When state is in the process of changing, progress is indicated by a moving pie chart


Download from GitHub

Pager Sliding TabStrip

Inspired by the new 4th version of the Android Play Store, Pager Sliding TabStrip is anInteractive paging indicator widget, compatible with the ViewPager from the Android Support Library.
Try out the sample application on the Play Store.



Download from GitHub

Fading ActionBar

FadingActionBar is a library which implements the cool fading action bar effect that can be seen in the new Play Music app.
This library uses the techniques outlined by Cyril Mottier in a recent blog post.
For reasons of backwards compatibility this library relies on ActionBarSherlock. If your app uses the native action bar, there is a fork for you.


Download from GitHub

MessageBar

An Android Toast replacement, similar to the one seen in the GMail app.
Features:
  • Messages are local to the Activity/Fragment the MessageBar is attached to
  • Messages can be queued
  • Can display a button, with a listener to react to clicks


Download from GitHub

HoloGraphLibrary

This library is an open-source set of graph types that are easy to add to your app, and in addition, look gorgeous. Themed in the much-loved Holo style of Android, the graphing library should fit in with any of your modern, standards-compliant apps.


Clone from Bitbucket

Sunday 22 December 2013

ActionBar Pull-to-Refresh

ActionBar-PullToRefresh provides an easy way to add a modern version of the pull-to-refresh interaction to your application, similar to the latest GMail app.




Download from GitHub
 

Cropper


The Cropper is an image cropping tool. It provides a way to set an image in XML and programmatically, and displays a resizable crop window on top of the image. Calling the method getCroppedImage() will then return the Bitmap marked by the crop window.
Developers can customize the following attributes (both via XML and programmatically):
  • appearance of guidelines in the crop window
  • whether the aspect ratio is fixed or not
  • aspect ratio (if the aspect ratio is fixed)
  • image resource
A public method to rotate the image by a specified number of degrees is also included. This can be used to provide the user with an option to fix the image orientation should Android miscalculate the intended orientation.
Download from GitHub

RangeBar


The RangeBar is similar to an enhanced SeekBar widget, though it doesn’t make use of the SeekBar. It provides for the selection of a range of values rather than a single value. The selectable range values are discrete values designated by tick marks; the thumb (handle) will snap to the nearest tick mark.
Download from GitHub

Friday 20 December 2013

Android StackBlur


Android StackBlur is a library that can perform a blurry effect on a Bitmap based on a gradient or radius, and return the result. The library is based on the code of Mario Klingemann.
Download from GitHub

MapNavigator Library



Easy to use library to get and display driving directions on Google Maps v2 in Android. This library gives you directions and displays the route on the map.
Download from GitHub

Wednesday 11 December 2013

left/right and up/down swiping navigation


public class Test extends Activity{

private GestureDetector gesturedetector = null;

View layout;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.test);

layout = (LinearLayout)findViewById(R.id.container);

gesturedetector = new GestureDetector(new MyGestureListener());

layout.setOnTouchListener(new OnTouchListener() {

@Override

public boolean onTouch(View v, MotionEvent event) {

gesturedetector.onTouchEvent(event);

return true;

}

});

}

public boolean dispatchTouchEvent(MotionEvent ev){

super.dispatchTouchEvent(ev);

return gesturedetector.onTouchEvent(ev);

}

class MyGestureListener extends GestureDetector.SimpleOnGestureListener{

private static final int SWIPE_MIN_DISTANCE = 150;

private static final int SWIPE_MAX_OFF_PATH = 100;

private static final int SWIPE_THRESHOLD_VELOCITY = 100;

@Override

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,

float velocityY) {

float dX = e2.getX()-e1.getX();

float dY = e1.getY()-e2.getY();

if (Math.abs(dY)<SWIPE_MAX_OFF_PATH &&

Math.abs(velocityX)>=SWIPE_THRESHOLD_VELOCITY &&

Math.abs(dX)>=SWIPE_MIN_DISTANCE ) {

if (dX>0) {

Toast.makeText(getApplicationContext(), Right Swipe”, Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getApplicationContext(), Left Swipe”, Toast.LENGTH_SHORT).show();

}

return true;

} else if (Math.abs(dX)<SWIPE_MAX_OFF_PATH &&

Math.abs(velocityY)>=SWIPE_THRESHOLD_VELOCITY &&

Math.abs(dY)>=SWIPE_MIN_DISTANCE ) {

if (dY>0) {

Toast.makeText(getApplicationContext(), Up Swipe”, Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getApplicationContext(), Down Swipe”, Toast.LENGTH_SHORT).show();

}

return true;

}

return false;

}

}

}

Saturday 30 November 2013

Android GPS with LocationManager to get current location – Example

In this article, we will create an Android application which displays latitude and longitude of the current location using GPS and Android’s LocationManager API.

An extension to this application is available in the article titled “Showing current location in Google Maps with GPS and LocationManager in Android“, where current location is displayed in Google Map.
This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )

Delete Android’s backward compatibility support library from the project, if exists
By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.

<resources>
    <string name="app_name">LocationFromGPS</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Location From GPS</string>
    <string name="str_tv_location">Current Location</string>
</resources>
 
Update the file res/layout/activity_main.xml
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="@string/str_tv_location"
        android:textStyle="bold" />
 
    <TextView
        android:id="@+id/tv_longitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_location"
        android:layout_centerHorizontal="true" />
 
    <TextView
        android:id="@+id/tv_latitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_longitude"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>
 
Update the file res/values/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme" />
</resources>
 
Update the file res/values-v11/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>
 
Update the file res/values-v14/styles.xml
 
<resources>
    <style name="AppTheme" parent="android:Theme.Holo" />
</resources>
 
Update the class MainActivity in the file src/in/wptrafficanalyzer/locationfromgps/MainActivitiy.java
 
package in.wptrafficanalyzer.locationfromgps;
 
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity implements LocationListener{
 
    LocationManager locationManager ;
    String provider;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Getting LocationManager object
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 
        // Creating an empty criteria object
        Criteria criteria = new Criteria();
 
        // Getting the name of the provider that meets the criteria
        provider = locationManager.getBestProvider(criteria, false);
 
        if(provider!=null && !provider.equals("")){
 
            // Get the location from the given provider
            Location location = locationManager.getLastKnownLocation(provider);
 
            locationManager.requestLocationUpdates(provider, 20000, 1, this);
 
            if(location!=null)
                onLocationChanged(location);
            else
                Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
 
        }else{
            Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
 
    @Override
    public void onLocationChanged(Location location) {
        // Getting reference to TextView tv_longitude
        TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
 
        // Getting reference to TextView tv_latitude
        TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
 
        // Setting Current Longitude
        tvLongitude.setText("Longitude:" + location.getLongitude());
 
        // Setting Current Latitude
        tvLatitude.setText("Latitude:" + location.getLatitude() );
    }
 
    @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
    }
}
 
Update the file AndroidManifest.xml
 
    package="in.wptrafficanalyzer.locationfromgps"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />
 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
 
Enable GPS in the emulator or device from Settings

Enabling GPS in Android 1.6 (Emulator)
Figure 5 : Enabling GPS in Android 1.6 (Emulator)


Set Longitude and Latitude of the location in Eclipse -> DDMS ( Perspective ) to run  this application in the emulator
Setting Longitude and Latitude in Eclipse ->DDMS Perspective
Figure 6 : Setting Longitude and Latitude in Eclipse ->DDMS Perspective

 Screenshot of the application
Showing Longitude and Latitude of the current location
Figure 7 : Showing Longitude and Latitude of the current location

 Download Source Code


 Reference
http://developer.android.com/guide/index.html
 
 
 
 
 
 
 




Friday 29 November 2013

Passing Objects in Intents: Parcelables and More

Hey everyone,
For this post, I thought I’d revisit the topic of Intents. In the past I’ve talked about passing Intents in between classes with simple, primitive data (see Passing Information between Activities) – turns out it’s a relatively easy task, and a core concept within the Android framework. However, the much harder task is passing your own classes (objects) in between Activities, and moreover, potentially passing lists of objects.
In this post, I’ll go through an example of writing an object that implements the Parcelable interface.
Consider a scenario where you have a list of Venues (i.e. Restaurants, Hotels, Clubs, anything with fields for lat, long, name, address, etc). Your user makes a request and gets back a list of these Venues. You then want to pass these results to a new Activity – maybe it’s a mapping Activity (as it was in my case), but regardless the goal is to pass this list of Venues from Activity A to Activity B without having to make the same request twice.
The first step is defining your object. The object must implement the Parcelable interface. Why you might ask? Well let’s step back and think about what’s happening here. Within Android, much of the inter-process (inter-Activity) communication is done through light weight data structures known as Parcels. In fact, both Intents and Bundles (two objects you’ve probably encountered before…) implement this Parcelable interface.
But how does this inter-process communication work? An Android process first converts an object into a byte stream which is then sent to another process (i.e. another Activity). This second process then reads in the byte stream and converts it back into an object: this exchange is more commonly known as serialization or marshalling. But how do the two Activities know what to do to serialize and de-serialize your object? For primitives like ints, doubles, even Strings, serialization is trivial as these primitives are already in byte form. And so this is where the Parcelable interface comes in.
By implementing the Parcelable interface, you are essentially giving the OS instructions on how to serialize and de-serialize your object. Conceptually this may be difficult to picture, but luckily Android has made the code for this super simply – in fact you are only required to override a few methods. With that, let’s take a look at what exactly needs to be done in the implementation:

public class ParcelableVenue implements Parcelable {
 
    private double lat, lon;
 
    private String name, address;
 
    public ParcelableVenue(double lat, double lon, String name, String address) {
        this.lat = lat;
        this.lon = lon;
        this.name = name;
        this.address = address;
    }
 
    public ParcelableVenue(Parcel source) {
        // TODO implement
    }
 
    public GeoPoint getGeoPoint() {
        return new GeoPoint((int) (lat * 1e6), (int) (lon * 1e6));
    }
 
    public String getName() {
        return name;
    }
 
    public String getAddress() {
        return address;
    }
 
    @Override
    public int describeContents() {                     // OVERRIDE METHOD #1
        return 0;
    }
 
    @Override
    public void writeToParcel(Parcel dest, int flags) { // OVERRIDE METHOD #2
        dest.writeDouble(this.lat);
        dest.writeDouble(this.lon);
        dest.writeString(this.name);
        dest.writeString(this.address);
    }
 
    public static final Parcelable.Creator<ParcelableVenue> CREATOR = new Parcelable.Creator<ParcelableVenue>() {
 
        // TODO implement
 
    };
 
}
 
So far we have the basic structure of our ParcelableVenue object – it has a few simple fields as well as some standard getters; nothing special there. You’ll then notice that there are two methods we need to override. The first is the describeContents() method. Typically returning 0 suffices unless you have numerous parcelable objects and require special serialization for some. The method itself is meant to return a bit mask that identifies the serialized object. In my case, I just return 0.
The second method is the writeToParcel(Parcel dest, int flags) method. The meat of the conversion happens here. In this method you are passed a destination Parcel which is eventually serialized and sent to the end process. Thus you simply need to write your object’s data into this parcel. Luckily, some simple write methods are given to you, such as writeDouble(), writeString(), writeInt(), writeIntArray(), etc. The flags parameter simply tells the writeToParcel() method how the object should be written.
Once these two methods are overridden, every class that implements the Parcelable interface then needs to have a static Parcelable.Creator object named CREATOR. Let’s step back one more time – where are we at this point? Well so far we’ve flattened the object and written it to a Parcel object. Our object is in essence nothing but a byte stream now, so the only thing that’s left to do is un-flatten it and convert it back into an object using this CREATOR object!
Our creator object is pretty simple and need only look like:

public class ParcelableVenue implements Parcelable {
 
    private double lat, lon;
 
    private String name, address;
 
    public ParcelableVenue(double lat, double lon, String name, String address) {
        this.lat = lat;
        this.lon = lon;
        this.name = name;
        this.address = address;
    }
 
    public ParcelableVenue(Parcel source) {
        // TODO implement
    }
 
    // ...
 
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeDouble(this.lat);
        dest.writeDouble(this.lon);
        dest.writeString(this.name);
        dest.writeString(this.address);
    }
 
    public static final Parcelable.Creator<ParcelableVenue> CREATOR = new Parcelable.Creator<ParcelableVenue>() {
 
        @Override
        public ParcelableVenue createFromParcel(Parcel source) {
            return new ParcelableVenue(source); // RECREATE VENUE GIVEN SOURCE
        }
 
        @Override
        public ParcelableVenue[] newArray(int size) {
            return new ParcelableVenue[size]; // CREATING AN ARRAY OF VENUES
        }
 
    };
 
}
 
And so we see that the very last step is simply to write another constructor for our ParcelableVenue class which initializes an object given a Parcel. This can be done with:
 
public class ParcelableVenue implements Parcelable {
 
    private double lat, lon;
 
    private String name, address;
 
    // ...
 
    public ParcelableVenue(Parcel source) {
        this.lat = source.readDouble();
        this.lon = source.readDouble();
        this.name = source.readString();
        this.address = source.readString();
    }
 
    // ...
 
}
The order here is important – the first double read will be the first double written as, again, it is a byte stream.
And that’s it! Once we have our ParcelableVenue, we can then do things like:

public class ClubsListActivity extends ListActivity {
 
    private List<Club> clubs;
 
    private Button mapViewButton;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.club_list);
 
        mapViewButton = (Button) findViewById(R.id.switch_map_view);
        mapViewButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // PREPARE NEW INTENT TO SEND TO MAP ACTIVITY
                Intent i = new Intent(ClubsListActivity.this, VenueMapView.class);
                 
                // INITIALIZE NEW ARRAYLIST AND POPULATE
                ArrayList<ParcelableVenue> overlays = new ArrayList<ParcelableVenue>();
                for (Club c : clubs) {
                    overlays.add(new ParcelableVenue(c.getLat(), c.getLon(), c.getName(), c.getAddress()));
                }
                 
                // EMBED INTO INTENT
                i.putParcelableArrayListExtra("venues", overlays);
                startActivity(i);
            }
 
        });
 
        SharedPreferences sp = getSharedPreferences(Constants.DB, Context.MODE_PRIVATE);
        double lat = (double) sp.getFloat(Constants.SP_PREV_LAT, (float) Constants.DEFAULT_LAT);
        double lon = (double) sp.getFloat(Constants.SP_PREV_LON, (float) Constants.DEFAULT_LON);
 
        // GET CLUBS NEAR YOU WITH LAT LON
    }
}
 
The receiving side then looks like:
 
public class VenueMapView extends MapActivity {
 
    private MapView map;
 
    private List<ParcelableVenue> venues;
 
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.mapview);
 
        SharedPreferences sp = getSharedPreferences(Constants.DB, Context.MODE_PRIVATE);
        double lat = (double) sp.getFloat(Constants.SP_PREV_LAT, (float) Constants.DEFAULT_LAT);
        double lon = (double) sp.getFloat(Constants.SP_PREV_LON, (float) Constants.DEFAULT_LON);
 
        map = (MapView) findViewById(R.id.venue_map); // INIT MAP
        map.setBuiltInZoomControls(true); // SET MAP CONFIGURATIONS
        map.getController().setCenter(new GeoPoint((int) (lat * 1e6), (int) (lon * 1e6)));
        int maxZoom = map.getMaxZoomLevel();
        map.getController().setZoom(maxZoom - 3);
 
        Intent i = getIntent(); // RETRIEVE OUR INTENT
        venues = i.getParcelableArrayListExtra("venues"); // GET PARCELABLE VENUES
 
        List<Overlay> mapOverlays = map.getOverlays();
        Drawable icon = this.getResources().getDrawable(R.drawable.good_pin);
 
        VenueOverlay vo = new VenueOverlay(icon, this); // INIT OVERLAY MARKERS
        List<OverlayItem> points = new ArrayList<OverlayItem>();
        for (ParcelableVenue v : venues) {
            OverlayItem o = new OverlayItem(v.getGeoPoint(), v.getName(), v.getAddress());
            points.add(o);
        }
 
        vo.addOverlayList(points);
 
        // ADD VENUE OVERLAYS TO MAP
        mapOverlays.add(vo);
    }
}
 
I won’t say too much about what I’m doing with my Maps Activity – maybe I’ll save this for a future tutorial. The important thing to see is how I send a list of ParcelableVenue objects, and then retrieve them on the other side. As you can probably see by now, there’s nothing hard code wise when implementing a Parcelable object. The difficulty typically stems from an incomplete understanding of how Android sends data from process to process – and this is understandable as almost all of this is abstracted away so that we only need to put simple values into Bundles and Parcels and voila things magically appear on the other side. But once you dig a little more into what’s happening behind the scenes, then all of this serialization and Parcelable implementation makes much more sense.
And with that I send you off again! Happy coding and hope this helped.