Monthly Archives: July 2014

Customizing listeners in your own class/object

I wanted to listen to a listeners which I implemented in my custom class without defining it on my MAIN class, so I come up with this idea of some sort of inheriting the listener and pass back to my main calling class. For the following example, I will show how to pass the listener (LocationManager.LocationListener) back to the MAIN. This is good if you want to have your custom class which will implements bunch of other listeners.

For example, I have Main and Class A.
Main – Main Class
MyLocationManager – Called from Main Class. Implements LocationManager.LocationListener
MyLocationManagerInterface – Where interface is declared

Main.java

public Main implements MyLocationManagerInterface{
  public MyLocationManager locationManager;

  public void onCreate(){
    locationManager = new MyLocationManager(this);
  }

  @Override
  public void onLocationChanged(Location location) {
    // Code here will be executed once LocationManager.LocationListener is called, even is not declared here.
  }
}

MyLocationManagerInterface.java

public interface MyLocationManagerInterface {
	public void onLocationChanged(Location location);
}

MyLocationManager.java

public MyLocationManager implements LocationListener{
  MyLocationManagerInterface myLocMgrIf;

  public MyLocationManager(MyLocationManagerInterface listener){
    myLocMgrIf = listener; // Init custom listener
    ......
    // Here you init all the LocationManager stuffs and request for updates.
  }

  @Override
  public void onLocationChanged(Location location) {
    myLocMgrIf.onLocationChanged(location); // Here you pass the location to custom interface
  }
}
Advertisements

Android MapFragment exception when clicked twice

My application crashed when I re-open the same MapFragment again twice.

E/AndroidRuntime(27409): Caused by: java.lang.IllegalArgumentException: Binary XML file line #5: Duplicate id 0x7f070039, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment

I solved it by declaring the view in my fragment where I called the map to static. By this way, I only create a new view if it is null, thus avoiding it to recreate the view again.

MapFragment.java

    static View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    	if(rootView==null){
    		rootView = inflater.inflate(R.layout.MapFragment, container, false);
    	}
        return rootView;
    }

MapFragment.xml

	<fragment 
	    android:id="@+id/mapview"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment"/>